使用jQuery更改img src而不多次加载图像?

时间:2016-03-09 11:42:07

标签: javascript jquery image

我使用jQuery编写了一个脚本,当窗口调整大小并且它正常工作时,它会改变HTML中img标签的src属性。但是,使用Chrome的开发人员工具,我注意到每个时间窗口调整大小,实际图像被加载!换句话说,如果用户反复调整窗口大小,则将一次又一次地加载图像。有没有办法避免这种情况,所以图像最多加载一次?

这是我的代码:

$(window).resize(function() {
    if ($(window).width() <= 480) {
    $(".on-demand-img").attr("src", "http://img1.coastalliving.timeinc.net/sites/default/files/image/2012/06/beaches/0612_best-beaches-kapalua-m.jpg");
} else if ($(window).width() <= 768) {
    $(".on-demand-img").attr("src", "https://s-media-cache-ak0.pinimg.com/736x/fa/6f/9a/fa6f9a5f7577a578bb7d63bf458d2905.jpg");
} else {
    $(".on-demand-img").attr("src", "https://imageserver.avenso.com/imageserver/bilder/paesaggi-sole-scattered-clouds-0:0:4b04507422128:1b762d.jpg");
}
});

2 个答案:

答案 0 :(得分:0)

试试这个

function setImageSrc(img, src){
    //images have a src-property you should use, 
    //instead of messing with the attribute
    $(img).each(function(){
        this.src === src || (this.src = src);
    });

    /*
    $(img).filter(function(){
        return this.src !== src;
    }).attr('src', src);
    */
}

$(window).resize(function() {
    var w = $(window).width();
    setImageSrc(".on-demand-img", 
        w <= 480? "http://img1.coastalliving.timeinc.net/sites/default/files/image/2012/06/beaches/0612_best-beaches-kapalua-m.jpg":
        w <= 768? "https://s-media-cache-ak0.pinimg.com/736x/fa/6f/9a/fa6f9a5f7577a578bb7d63bf458d2905.jpg":
        "https://imageserver.avenso.com/imageserver/bilder/paesaggi-sole-scattered-clouds-0:0:4b04507422128:1b762d.jpg"
    );
});

编辑:仍然有错误,我找到了。 src-property总是包含完整路径;代码将以相对路径失败。

答案 1 :(得分:0)

这些事情需要通过css完成:

基本上,你以覆盖所有内容的方式构建你的dom,然后通过媒体查询显示你想要的东西。

另一个更优雅的解决方案可能是使用srcset but IE doesn't support it

&#13;
&#13;
.visible-xs,
.visible-lg,
.visible-sm { display: none; }

@media (max-width: 500px) {
  .visible-xs {
    display: block;
  }
}

@media (min-width: 501px) and (max-width: 1199px) {
  .visible-sm {
    display: block;
  }
}

@media (min-width: 1200px) {
  .visible-lg {
    display: block;
  }
}
&#13;
<img class="visible-lg" src="pat/to/lg" alt="BIG IMAGE">
<img class="visible-sm" src="pat/to/sm" alt="MEDIUM IMAGE">
<img class="visible-xs" src="pat/to/xs" alt="SMALL IMAGE">
&#13;
&#13;
&#13;