javascript - 将滚动事件绑定到特定元素
问题描述
我目前正在寻找仅当鼠标悬停在图像上时才向图像序列添加滚动事件。我不希望页面滚动,而只是滚动图像。
$(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>
解决方案
我写了这个小例子,说明如何捕获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>
推荐阅读
- mysql - Node.js:使用来自 aws 的密钥加密字段
- python - 尝试将文件从云存储读取到 Pandas 时出现 google.auth.exceptions.RefreshError
- javascript - JS:实现哈希表并获取 NaN
- html - SASS:在文件夹中搜索文件夹并定位所有文件
- linux - 实例在根目录下没有附加卷
- javascript - 如何在 jquery 中制作手风琴
- bash - 清理 json 的字符串
- java - 将列表拆分为 4 个甚至单独的列表
- reactjs - react-admin 中的事件记录/跟踪?
- apache-camel - doTry/doCatch 和全局 onException 行为