我正在创建带有空源的图像标签,并从我的JS文件中更新img标签的src。更新源时,如果找不到该图像,则要显示默认图像。
<img src="" onerror="this.onerror=null; this.onload=null; this.src='images/logo/1.png';"/>
使用上面的代码,在加载HTML页面时,由于未设置src,因此显示的是默认图像。我不希望它在初始页面加载时显示。我只想在设置了图像src并且找不到设置的源之后才显示默认图像。
我尝试了以下代码,但还是没有运气。看起来,this.src具有我们index.html位置的值。
<img src="" onerror="this.onerror=null; this.onload=null; if (!this.src) this.src='images/logo/1.png';"/>
答案 0 :(得分:0)
您可以像这样将display
的{{1}}属性设置为img
,方法是将此属性添加到图像标签none
style="display:none;"
在JS文件中,您可以在设置<img src="" onerror="this.onerror=null; this.onload=null; if (!this.src) this.src='images/logo/1.png';" style="display:none;"/>
属性后设置display:block;
这是一个带有按钮的示例(按下按钮3秒后图像显示)
src
var elem = document.getElementById("myImg");
elem.src = "https://via.placeholder.com/150"; //set the source
function myFunction(){
elem.style.display = "block"; //set the style of image to block
}
答案 1 :(得分:0)
您可以尝试一下。如果为空,它将更改src
中的img
。
这是一个例子
<img src="" onerror="this.onerror=null; this.onload=null; if (!this.attributes.src.value) this.attributes.src.value='https://www.w3schools.com/jsref/compman.gif';"/>