加载图像后,替换图像src

时间:2015-09-04 09:51:31

标签: jquery

我有这个代码,只有在加载后才能在多个图像中淡入淡出。即使从缓存加载图像,也会触发它。

$(".image-class").one("load", function() {
    $(this).fadeIn("slow");
}).each(function() {
    if(this.complete) $(this).load();
});

现在,当加载完成时,如果图像的宽度小于130,我想在其中加载另一个图像。在加载第二张图像之前,不会显示任何内容。

$(imgID).one("load", function() {
    // check if image is too small
    if($(this).width() < 130 ){
        $(this).attr("src","larger_image.jpg");
    }else{
        $(this).fadeIn("slow");
    }
}).each(function() {
  if(this.complete) $(this).load();
});

如果宽度<1,则会加载不同的照片。但是它似乎永远不会触发load第二张图像。 fadeIn永远不会触发第二张图片,因此它从未显示过。

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

因为您正在使用.one()来注册处理程序,这将只触发处理程序一次,之后处理程序被丢弃

var imgID = 'img';
$(imgID).on("load", function() {
  // check if image is too small
  if ($(this).width() < 130) {
    $(this).attr("src", "//placehold.it/150x64");
  } else {
    $(this).fadeIn("slow").off('load');
  }
}).hide().each(function() {
  if (this.complete) $(this).load();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="//placehold.it/64x64" />

相关问题