簡體   English   中英

替換損壞的圖像並使用javascript調整錯誤圖像的大小

[英]Replacing a broken image and resizing the error image with javascript

好的,所以我知道這個問題已被問到separetly但我正在嘗試使用javascript通過更改src屬性用另一個具有不同尺寸的圖像替換損壞的圖像。 這是我的代碼的一部分:

加價:

...
<img id="error-img" class="img-header" onerror="imgError(this);" alt="Header" src="images/header.png">
...

樣式:

...
.img-header { width: 54px; height: 64px; }
...

JAVASCRIPT:

...
function imgError(image) {
image.onerror = "";
image.src = "/images/broken.png";
return true;
}
...

所以我需要的是在這個函數中包含一段代碼,這樣當圖像被替換時,新圖像的尺寸設置正確但不是54x64px。

編輯:

謝謝你的回答,但我忘了提到broken.png圖片的大小:寬度:276px高度:45px。

...
function imgError(image) {
image.onerror = "";
image.src = "/images/broken.png";
// set width/height
image.style.width = "50px";
image.style.height = "50px";
// or add class name
image.className = "img-error";
return true;
}
...

CSS

...
.img-header { width: 54px; height: 64px; }
.img-error  { width: 40px; height: 40px; }
...

如果您希望替換圖像具有自己的寬度/高度而不是繼承自.image-header類,則可以選擇以下幾種:

1)。 clear className:

image.className = '';

http://jsfiddle.net/gGP5D/

2)。 添加新的類名:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/broken.png";
    image.className += ' replacement-image';
}

http://jsfiddle.net/gGP5D/1/

如果已知新維度,則可以定義新的維度,或將寬度和高度重置為auto值。

您可以執行以下操作將圖像的CSS屬性重置為錯誤圖像的大小:

function imgError(image) {
  image.onerror = "";
  image.src = "/images/broken.png";
  elem.style.width = "100px"; //use whatever size the new image is here
  elem.style.height= "100px"; //use whatever size the new image is here
  return true;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM