首页 > 解决方案 > 将滚动事件绑定到特定元素

问题描述

我目前正在寻找仅当鼠标悬停在图像上时才向图像序列添加滚动事件。我不希望页面滚动,而只是滚动图像。

$(document).ready(function () {
  var pictureCount = $('#container img').length;
  var scrollResolution = 50;


  animateImage();
});
function animateImage() {
    var currentScrollPosition = window.pageYOffset;
    var imageIndex = Math.round(currentScrollPosition / scrollResolution);

    if (imageIndex >= pictureCount) {
        imageIndex = pictureCount - 1; // Select last image
    }

    $("#container img").hide();
    $("#container img").eq(imageIndex).show();
}

$(window).bind('scroll', function() {
    animateImage();
});
<div id="container">
   <img src="frames/noindex_basset_02_img000.jpg" class="animated">
</div>  

标签: javascriptjquery

解决方案


我写了这个小例子,说明如何捕获wheel容器上的事件并根据阈值和滚动方向交换事物。

!function(){
  var totalVerticalDistanceScrolled = 0;
  //changable to configure how sensitive the scroll change is
  var scrollDistanceToChangeElements = 200;
  var $elementsToChange = $('.animated');
  
  //capture the wheel event when it is over the container
  $('#container').on('wheel', function(e){
    //sum up how much the user has scrolled.  scrolling up is negative
    totalVerticalDistanceScrolled += e.originalEvent.deltaY;
    
    //in the threshold has been met either up or down, swap elements
    if (Math.abs(totalVerticalDistanceScrolled) >= scrollDistanceToChangeElements) {
      var currentElementIndex = $elementsToChange.filter('.active').index();
      var nextElementIndex;
      
      //hide the currently shown element
      $elementsToChange.eq(currentElementIndex).removeClass('active');

      if (totalVerticalDistanceScrolled > 0) {
        //get the next element index, wrap back to the first element at the end
        nextElementIndex = (currentElementIndex + 1) % $elementsToChange.length;
      } else {
        //get the previous element index, wrap back to the last element at the end
        nextElementIndex = ( currentElementIndex || $elementsToChange.length ) - 1;
      }

      //show the next desired element
      $elementsToChange.eq(nextElementIndex).addClass('active');
      //clear out the total distance so the user can change direction if they want
      totalVerticalDistanceScrolled = 0;
    }
  });
}();
.animated {
  display: none;
  min-width:200px;
  min-height: 200px;
}

.animated.active { display: inline-block; }

.red { background-color: red; }
.green { background-color: green; }
.blue { background-color: blue; }

#container {
  max-width: 200px;
  max-height: 200px;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="animated red active"></div>
  <div class="animated green"></div>
  <div class="animated blue"></div>
</div>


推荐阅读