首页 > 解决方案 > 元素不会隐藏 - Jquery

问题描述

我有几个包装器,其中包含加载真实图像时的加载 gif。

我还有一些 jquery 应该在真实图像加载后隐藏 gif,但加载 gif 不会隐藏。如果我将 $(this) 替换为 $(".displayImg") 它将起作用,但它会影响所有加载的 gif。为什么 $(this) 让它不隐藏?

$('.displayImg').on("load", function() {
  $(this).parent().find(".loadingImage").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrapper'>
  <img class='loadingImage' src='https://media0.giphy.com/media/xTk9ZvMnbIiIew7IpW/giphy.gif'>

  <img class='displayImg' src='https://via.placeholder.com/350x150'>
</div>

<div class='wrapper'>
  <img class='loadingImage' src='https://media0.giphy.com/media/xTk9ZvMnbIiIew7IpW/giphy.gif'>

  <img class='displayImg' src='https://via.placeholder.com/200x100'>
</div>

标签: jqueryhtml

解决方案


您根本不需要使用 Javascript。一种方法是将加载程序作为背景图像。当实际图像加载时(假设它没有任何透明度),它将覆盖加载器。您可以随意调整装载机的大小和位置。

.wrapper1 {
  width: 350px;
  height: 150px;
  background-image: url(https://media0.giphy.com/media/xTk9ZvMnbIiIew7IpW/giphy.gif);
}

.wrapper2 {
  width: 200px;
  height: 100px;
  background-image: url(https://media0.giphy.com/media/xTk9ZvMnbIiIew7IpW/giphy.gif);
  background-position: 50% 50%;
  background-size: contain;
  background-repeat: no-repeat;
}
<div class='wrapper1'>
  <img class='displayImg' src='https://via.placeholder.com/350x150'>
</div>

<div class='wrapper2'>
  <img class='displayImg' src='https://via.placeholder.com/200x100'>
</div>


推荐阅读