首页 > 解决方案 > 用户上下滚动时更改图像

问题描述

我有两张图片(一个封闭的盒子和一个打开的盒子)与本网站横幅下的动画非常相似。当用户上下滚动页面时,图像会发生变化。我将如何创造这种效果?

我曾尝试使用 Jquery 鼠标滚轮,但这对我不起作用。任何建议将不胜感激!

打开盒子图像

封闭的盒子图像

标签: javascripthtmljquerycsswordpress

解决方案


这是您可以学习学习的代码示例:

     var lastScrollTop = 0, delta = 1;
     $("div").scroll(function(){

         var nowScrollTop = $(this).scrollTop();
 //    console.log(nowScrollTop);
         if(Math.abs(lastScrollTop - nowScrollTop) >= delta){
            if (nowScrollTop > lastScrollTop){
                // SCROLLING DOWN 
        $('#image img').attr('src', "https://supamama.co.za/img/product/closed.png");
            } else {
                // SCROLLING UP 
        $('#image img').attr('src', "https://supamama.co.za/img/product/open.png");
            }
         lastScrollTop = nowScrollTop;
         }
     });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>

<div style="border:1px solid black;width:470px;height:550px;overflow:scroll;">
<div>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>
<div>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>
   <div id="image" >
      <img src = "https://supamama.co.za/img/product/open.png" height = "250" width = "370"  />
<div>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>
<div>In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>
      </div>
  </div>
   </body>


推荐阅读