好的,所以我知道这个问题已被单独询问,但我正在尝试使用 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
图像的大小:
宽度:276 像素高度:45 像素。
最佳答案
为此,您可以使用 image.style
设置宽度或高度,或使用 image.className
为其分配一个类。
...
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; }
...
关于javascript - 替换损坏的图像并使用 javascript 调整错误图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077313/