奇怪的jQuery问题

时间:2012-05-29 07:53:48

标签: jquery

我已将此脚本插入包含50张小图片(从16x16px到50x50px)的网页中:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('img').css('opacity', '0.0').load(function(){
    $(this).animate({'opacity': '1.0'});
});         
});
</script>

问题是不是每个图像都被加载而有些图像没有出现。

为什么?

5 个答案:

答案 0 :(得分:4)

当您将不透明度设置为0时,某些图片可能已经加载,因此他们的onload处理程序已经运行,您没有机会再次显示它们。

答案 1 :(得分:3)

有可能从缓存加载某些图像。如果图像是从cach加载的,那么load事件将在dom ready事件之前触发。一种方法是

$('img').css('opacity', '0.0').one('load',function(){
    $(this).animate({'opacity': '1.0'});
}).each(function() {
   if(this.complete) $(this).load();
});

这将遍历图像并检查它们是否已从缓存加载,如果是,则它将为这些图像触发加载事件。

我使用$.one只运行一次事件处理程序,因为我们不需要执行多次。

<强>更新

if(this.complete)将检查图片是否已加载(如果已缓存),如果是,则会立即触发load事件。

没有从缓存中加载,浏览器会在加载后为它们激活load事件。

因此上面的代码将涵盖所有图像,缓存与否。

答案 2 :(得分:1)

在CSS样式中设置默认的opacity值,而不是通过javascript。之后,使用animate

<style>
     img { opacity:0 }
</style>

<script type="text/javascript">
$(document).ready(function(){
    $('img').load(function(){
        $(this).animate({'opacity': '1.0'});
    });         
});
</script>

答案 3 :(得分:0)

使用预加载图片javascript代码...

<script type="text/javascript">
if (document.images) {
    img1 = new Image();
    img1.src = "image.jpg";
    img2 = new Image();
    img2.src = "image2.jpg";
}
</script>

现在所有图片都预先加载到客户端计算机中并且始终可见....

OR

灵活数组

function preload(images) {
    if (document.images) {
        var i = 0;
        var imageArray = new Array();
        imageArray = images.split(',');
        var imageObj = new Image();
        for(i=0; i<=imageArray.length-1; i++) {
            //document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
            imageObj.src=images[i];
        }
    }
}

答案 4 :(得分:0)

您可以更好地设置css中图像的不透明度,如

img {
opacity:0
}

然后使用您的代码

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('img').load(function(){
    $(this).animate({'opacity': '1.0'});
});         
});
</script>