I am trying to create a browser plug-in which keeps .gifs faded out until they are fully loaded. Once the images are loaded, they fade in.

HTML

<img src="http://media.tumblr.com/6ced3000389da1433b13c8a18bfeaf75/tumblr_inline_muf6jmZS8m1rc3mra.gif" alt="">

<img src="http://4.bp.blogspot.com/-fYJrkNWec08/T9EYOmNGPNI/AAAAAAAAC04/UtdRRM8a3hc/s640/cat-fat-dancing-cat-gif.gif" alt="">

jQuery

$("img[src$='gif']").each( function() {
    $(this).css({'opacity': '0.05'});
    $(this).load( function() {
        $(this).fadeIn();
    });
});

JS Fiddle

However, the images don't fade in as the .load function is never activated.

What am I doing wrong? The jQuery docs do mention some cross browser issues, but this was tested in the latest version of both Chrome and Safari and both failed.

有帮助吗?

解决方案

Using a little plain javascript is usually easier when checking for image.onload :

$("img[src$='gif']").each( function() {
    var self = $(this).css({'opacity': '0.05'});

    var img = new Image();
    img.onload = function() {
        self.fadeTo('fast', 1)
    }
    img.src = this.src;

    if (img.complete) img.onload();
});

And note that fadeIn() only works with hidden images, not images that are visible with a lower opacity, which is the real issue with your code.

FIDDLE

其他提示

Try this. The load function is activated and you can do whatever you want after

$("img[src$='gif']").each( function() {
        $(this).css({'opacity': '0.05'});
        $(this).one('load', function() {
      alert('Image Loaded'); 
    }).each(function() {
      if(this.complete) $(this).load();
    });
    });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top