简体   繁体   English

使用JavaScript动态更改img标签中的显示样式

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

I show links to 240 images on a page. 我在页面上显示指向240张图像的链接。 The real images are uploaded by users. 真实图像由用户上传。 I tried to avoid showing an empty image if users did not upload it yet. 如果用户尚未上传,我试图避免显示空白图像。 jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript. jQuery由于冲突而无法为我工作,因此我必须使用纯JavaScript来完成。

image(s) links: 图片链接:

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

My JavaScript: 我的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";
    }
}

The style photo240off equals to display:none . 样式photo240off等于display:none

Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. 现在,每当有图像丢失时,所有图像都会变成photo240off样式,我只希望隐藏丢失的图像。 So there is something wrong with my script. 因此我的脚本有问题。

(the overall script works well, because I get the alert). (整体脚本运行良好,因为我得到了警报)。

Use this to get the image with the error. 使用this来获取带有错误的图像。

Change to: 改成:

onerror="imgError(this)"

Then the function can be: 然后该函数可以是:

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

You need to reference the image from your onerror call and change the class only for that one. 您需要从onerror调用中引用该图像,并仅更改该图像的类。

Something like this: 像这样:

HTML HTML

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

JS JS

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM