我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
当前回答
我是否可以建议您将其重新加载到非dom图像对象中?如果它被缓存,这将完全不花费时间,onload仍然会触发。如果它没有被缓存,它将在图像加载时触发onload,这应该与图像的DOM版本完成加载的时间相同。
Javascript:
$(document).ready(function() {
var tmpImg = new Image() ;
tmpImg.src = $('#img').attr('src') ;
tmpImg.onload = function() {
// Run onload code.
} ;
}) ;
更新(以处理多个图像和正确顺序的onload附件):
$(document).ready(function() {
var imageLoaded = function() {
// Run onload code.
}
$('#img').each(function() {
var tmpImg = new Image() ;
tmpImg.onload = imageLoaded ;
tmpImg.src = $(this).attr('src') ;
}) ;
}) ;
其他回答
如果你想要一个纯CSS的解决方案,这个技巧非常有效——使用transform对象。这也适用于图像缓存与否:
CSS:
.main_container{
position: relative;
width: 500px;
height: 300px;
background-color: #cccccc;
}
.center_horizontally{
position: absolute;
width: 100px;
height: 100px;
background-color: green;
left: 50%;
top: 0;
transform: translate(-50%,0);
}
.center_vertically{
position: absolute;
top: 50%;
left: 0;
width: 100px;
height: 100px;
background-color: blue;
transform: translate(0,-50%);
}
.center{
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: red;
transform: translate(-50%,-50%);
}
HTML:
<div class="main_container">
<div class="center_horizontally"></div>
<div class="center_vertically"></div>
<div class="center"></div>
</div>
</div
Codepen例子
Codepen LESS的例子
我找到了一个解决方案https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12 (此代码直接取自注释)
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;
如果你想这样做,我可以给你一个小建议:
<div style="position:relative;width:100px;height:100px">
<img src="loading.jpg" style='position:absolute;width:100px;height:100px;z-index:0'/>
<img onLoad="$(this).fadeIn('normal').siblings('img').fadeOut('normal')" src="picture.jpg" style="display:none;position:absolute;width:100px;height:100px;z-index:1"/>
</div>
如果你在浏览器缓存图片时这样做,总是显示img没有问题,但在真实图片下加载img。
如果src已经设置,则在绑定事件处理程序之前,事件就会在缓存的情况下触发。为了解决这个问题,你可以循环检查和触发基于.complete的事件,就像这样:
$("img").one("load", function() {
// do stuff
}).each(function() {
if(this.complete) {
$(this).load(); // For jQuery < 3.0
// $(this).trigger('load'); // For jQuery >= 3.0
}
});
注意从.bind()到.one()的变化,因此事件处理程序不会运行两次。
我自己也有这个问题,到处寻找一个解决方案,不涉及杀死我的缓存或下载插件。
我没有立即看到这个帖子,所以我发现了一些其他的东西,这是一个有趣的修复,(我认为)值得张贴在这里:
$('.image').load(function(){
// stuff
}).attr('src', 'new_src');
实际上,我从这里的评论中得到了这个想法:http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/
我不知道为什么它能工作,但我已经在IE7上测试了这个,在它现在工作之前它在哪里坏了。
希望能有所帮助,
Edit
公认的答案实际上解释了原因:
如果src已经设置,那么在绑定事件处理程序之前,事件就会在缓存中触发。