JS:悬停的图像无法顺利加载

问题描述 投票:0回答:2

我正在使用JS在悬停时更改图片...但是悬停的图片无法顺利加载。任何帮助表示赞赏。

    <script type="text/javascript">
      $( document ).ready(function() {
          $('.img-grey').on({
            mouseenter: function (e) {
              var greysrc = $(this).attr('src');
              var colorsrc = greysrc.replace("1.jpg", "2.jpg")
              $(this).attr('src', colorsrc);
            },
            mouseleave: function (e) {
              var colorsrc = $(this).attr('src');
              var greysrc = colorsrc.replace("2.jpg", "1.jpg")
              $(this).attr('src', greysrc);
            }
          })
      });
    </script>
javascript image hover load
2个回答
0
投票

或者,可以使用css解决此任务。检查css属性选择器https://www.w3schools.com/css/css_attribute_selectors.asp

您只需要创建下一个html结构:

<div class="container">
    <img src="1path-to-1.jpg" />
    <img src="1path-to-2.jpg" />
</div>
<div class="container">
    <img src="2path-to-1.jpg" />
    <img src="2path-to-2.jpg" />
</div>

请参阅附件摘录

.container [src$="2.jpg"] {
 display: none;
}

.container:hover [src$="1.jpg"] {
 display: none;
}

.container:hover [src$="2.jpg"] {
 display: inline;
}

.container {
 float: left;
}
<div class="container">
  <img src="https://www.gravatar.com/avatar/8aecf6164a04433529bd7702f1b5f59a?s=128&d=identicon&r=PG&f=1&1.jpg" />
  <img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>

<div class="container">
  <img src="https://www.gravatar.com/avatar/b8367b2f25ceee4d54595495b4e51312?s=128&d=identicon&r=PG&f=1&1.jpg" />
  <img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>

<div class="container">
  <img src="https://www.gravatar.com/avatar/f20fc11c3f294bdebe4351e7ca240678?s=128&d=identicon&r=PG&f=1&1.jpg" />
  <img src="https://www.gravatar.com/avatar/8aecf6164a04433529bd7702f1b5f59a?s=128&d=identicon&r=PG&f=1&2.jpg" />
</div>

0
投票

如果要预加载图像,则应将它们放入DOM中或添加为背景属性。这是您的代码的修改版本,它在现有的旁边添加了隐藏的<img />元素。我没有运行它,但它应该工作

$( document ).ready(function() {
    $('.img-grey').map(function () {
      var temp = document.createElement('img');
      temp.src = this.src.replace("1.jpg", "2.jpg");
      temp.style.display = 'none';
      $(this).parent().append(temp);
      return this;
    }).on({
      mouseenter: function (e) {
        var greysrc = $(this).attr('src');
        var colorsrc = greysrc.replace("1.jpg", "2.jpg")
        $(this).attr('src', colorsrc);
      },
      mouseleave: function (e) {
        var colorsrc = $(this).attr('src');
        var greysrc = colorsrc.replace("2.jpg", "1.jpg")
        $(this).attr('src', greysrc);
      }
    })
});
© www.soinside.com 2019 - 2024. All rights reserved.