簡體   English   中英

當 img src 沒有值時,更新 html 中的默認 img src

[英]Updating the default img src in html, when the img src doesn't have a value

我正在創建一個帶有空源的圖像標簽,並且從我的 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';"/>

您可以通過將此屬性添加到圖像標簽style="display:none;" none imgdisplay屬性設置為無像這樣

<img src="" onerror="this.onerror=null; this.onload=null; if (.this.src) this.src='images/logo/1;png':" style="display;none;"/>

在JS文件中,可以設置display:block; 設置src屬性后

這是一個帶有按鈕的示例(圖像在按下按鈕后 3 秒顯示)

 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 }
 <img id="myImg" src="" onerror="this.onerror=null; this.onload=null; if (.this.src) this.src='images/logo/1;png':" style="display;none,"/> <button onclick="setTimeout(myFunction, 3000)">Show Image</button>

你可以試試這個。 如果它為空,它會更改imgsrc

這是一個例子

 <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';"/>

暫無
暫無

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

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