图像加载功能不起作用

时间:2018-06-15 14:55:10

标签: javascript jquery image-loading

目标: 加载.thumbnail div中的图像后,红色边框应变为绿色

的jsfiddle: https://jsfiddle.net/3k8xy2cf/

var container;
var img;

$("#products .thumbnail").each(function() {
  container = $(this);
  img = new Image();
  img.src = $(container).find('img').attr('src');
  img.onload = function() {
    $(container).addClass('loaded');
  }
});
.product {
  float: left;
  border: 5px solid red;
}
.product.loaded {
  border-color: green;
}
.product img {
  width: 25%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="products">
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/600x600" alt="">
    </div>
  </div>
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/800x800" alt="">
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

您的代码比它需要的复杂得多。您不需要each()循环,并且您当然不需要从已存在的元素中创建新的img元素。

相反,您可以在load()元素上使用img事件处理程序,将类添加到父.thumbnail,如下所示:

$('#products .thumbnail img').on('load', function() {
  $(this).closest('.thumbnail').addClass('loaded');
});
.thumbnail {
  border: 2px solid #C00;
}

.thumbnail.loaded {
  border-color: #0C0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="products">
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/125x125" alt="">
    </div>
  </div>
  <div class="product">
    <div class="thumbnail">
      <img src="https://placehold.it/150x150" alt="">
    </div>
  </div>
</div>