簡體   English   中英

使用JavaScript動態更改img標簽中的顯示樣式

[英]Using JavaScript to dynamically change display style in img tags

我在頁面上顯示指向240張圖像的鏈接。 真實圖像由用戶上傳。 如果用戶尚未上傳,我試圖避免顯示空白圖像。 jQuery由於沖突而無法為我工作,因此我必須使用純JavaScript來完成。

圖片鏈接:

<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">

我的JavaScript:

function imgError()
{
    alert('The image could not be loaded.');
    var _aryElm=document.getElementsByTagName('img');  //return an array with every <img> of the page
    for( x in _aryElm) {
        _elm=_aryElm[x];
        _elm.className="photo240off";
    }
}

樣式photo240off等於display:none

現在,每當有圖像丟失時,所有圖像都會變成photo240off樣式,我只希望隱藏丟失的圖像。 因此我的腳本有問題。

(整體腳本運行良好,因為我得到了警報)。

使用this來獲取帶有錯誤的圖像。

改成:

onerror="imgError(this)"

然后該函數可以是:

function imgError(el) {
    alert('The image could not be loaded.');
    el.className = "photo240off";
}

您需要從onerror調用中引用該圖像,並僅更改該圖像的類。

像這樣:

HTML

<img class="photo240" src="example.jpg" onerror="imgError(this)">

JS

function imgError(el) {
    el.className="photo240off";
}

暫無
暫無

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

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