我正在尝试仅在图像加载后使用JavaScript显示。
我尝试通过向其添加一个类( hidden ),然后使用 addEventListener 来实现该目标,并在加载后删除该类。
代码如下:
imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].classList.add('hidden');
imgs[i].addEventListener('load', this.classList.remove("hidden"));
}
重新加载页面后,第一张图像消失,表明已添加该类,但下一行出了问题。 在控制台中,我得到:未捕获的TypeError:无法在下一行读取未定义的属性'remove'。
答案 0 :(得分:1)
// this code runs AFTER the data URI has loaded so it can be simple
document.querySelectorAll('img').forEach(function(img) {
img.addEventListener('load', function() {
this.classList.remove("hidden");
});
img.src = img.getAttribute("data-src");
});
.hidden {
visibility: hidden;
}
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==" data-src="https://via.placeholder.com/468x60?text=Image1" class="hidden" />
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==" data-src="https://via.placeholder.com/468x60?text=Image2" class="hidden" />
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==" data-src="https://via.placeholder.com/468x60?text=Image3" class="hidden" />
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg==" data-src="https://via.placeholder.com/468x60?text=Image4" class="hidden" />
答案 1 :(得分:0)
如前所述,您没有正确使用.addEventListener
。另外,请勿使用getElementsByTagName()
,因为它会返回活动节点列表。而是使用.querySelectorAll()
。
下面,将引用同一图像的4种不同分辨率。您将看到代码按预期工作。
imgs = document.querySelectorAll('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].addEventListener('load', function(){
this.classList.remove("hidden")
});
}
img { border:1px solid grey; width:75px; }
.hidden { visibility:hidden; }
<img src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/12710/web.jpg" class="hidden">
<img src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/12704/large_web.jpg" class="hidden">
<img src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/12707/print.jpg" class="hidden">
<img src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/12702/full_jpg.jpg" class="hidden">