繁体   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