每个图像加载时的JS事件

时间:2015-06-22 21:59:10

标签: jquery

现在我有一些代码在页面加载后执行,如下所示:

$(window).load(function() {

    $('.featuredimage').each(function(){
        var img_width = $(this).width();
        var img_height = $(this).height();

        if (img_height >= img_width){
            $(this).addClass("artistthirdtall");

        };

        if (img_height < img_width){
            $(this).addClass("artistthirdwide");      
        };

    });


});

然而,页面上有一些大图像,并且可以有一个&#34;闪烁&#34;因为图像被Javascript操纵。

理想情况下,我希望在每个图像加载时运行此函数(而不是等待所有图像加载)。

我查看了这个jQuery加载事件页面:https://api.jquery.com/load-event/,看起来使用它检查图像是否加载有一些严重问题?但是给出的例子基本上就是我试图做的事情。

使用给定的示例代码是否安全?

由于

PS - 我是一名自学成才的开发者,并且不知道那么多,如果我说了些蠢话,请原谅我。

1 个答案:

答案 0 :(得分:0)

我会在你的图片中添加一个类来隐藏它们,直到它们准备好。然后淡入它们。根据以下内容划伤$ .ready加载:Official way to ask jQuery wait for all images to load before executing something

<img src="foo" class="featuredimage ui-hidden-accessible"

    $(window).load(function() {
        $('.featuredimage').each(function() {
        var img_width = $(this).width();
        var img_height = $(this).height();

        if (img_height >= img_width){
            $(this).addClass("artistthirdtall").fadeIn(); /* added fadeIn() */
        };

        if (img_height < img_width){
            $(this).addClass("artistthirdwide").fadeIn(); /* added fadeIn() */     
        };
    });
});