[英]How to make an element scroll when scrolling body
When the mousewheel is scrolled on the body of a page this event can be captured. 当鼠标滚轮在页面正文上滚动时,可以捕获此事件。 I'd like this event to trigger a target element to scroll. 我希望此事件触发目标元素滚动。
#target is a scrollable element that is never the height of the page. #target是一个可滚动的元素,永远不会位于页面的高度。 I'd like to capture the mousescroll event anywhere on the page so even if the cursor is not over the element the element still scrolls. 我想捕获页面上任何位置的mousescroll事件,因此即使光标不在元素上,该元素仍会滚动。
$( 'body' ).on( 'DOMMouseScroll mousewheel', function () {
// Scroll #target instead of body
});
Thanks to this post for showing me how to capture scroll wheel events: Capturing Scroll Wheel Events 感谢这篇文章向我展示了如何捕获滚轮事件: 捕获滚轮事件
You can have a look at this. 您可以看一下。
http://jsfiddle.net/ZtGva/7/ http://jsfiddle.net/ZtGva/7/
JS JS
$(function () {
var myCounter = 0,
myOtherCounter = 0;
var scroll = 0;
$("#target").scroll(function () {
myCounter = myCounter + 1;
$("#log").html("<div>Handler for .scroll() called " + myCounter + " times.</div>");
});
//Firefox
// $(document).bind(...) this works as well
$('#body').bind('DOMMouseScroll', function (e) {
if (e.originalEvent.detail > 0) {
scrollDown();
} else {
scrollUp();
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#body').bind('mousewheel', function (e) {
if (e.originalEvent.wheelDelta < 0) {
scrollDown();
} else {
scrollUp();
}
//prevent page fom scrolling
return false;
});
function scrollDown() {
//scroll down
console.log('Down ' + scroll);
if (scroll < $('#target').find('div').height() - $('#target').height() + 20) {
scroll = $('#target').scrollTop() + 5;
$('#target').scrollTop(scroll);
}
};
function scrollUp() {
//scroll up
console.log('Up ' + scroll);
if (scroll > 0) {
scroll = $('#target').scrollTop() - 5;
$('#target').scrollTop(scroll);
}
};
});
Note I added a div for height calculation 注意我添加了一个div用于高度计算
<div id="target"><div>.... </div></div>
You can clean up this code a bit by caching some jquery variables but the idea is there 您可以通过缓存一些jquery变量来稍微清理一下此代码,但是这个想法在那里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.