我想在用户向上滚动时(在全屏高度页面中)调用my_function1,或在用户向下滚动时调用my_function2。
当我打开包含此代码的页面时,它将始终立即在else {}中运行函数(在此代码示例中为“slide_down();”。我该怎么办?
var position = $(window).scrollTop();
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > position) {
slide_up();
} else {
slide_down();
}
position = scroll;
});
答案 0 :(得分:0)
以下是检测用户是否向上或向下滚动并且也适合移动设备的代码。
console.log()
在代码片段中起作用,因为每个滚动的像素都会调用日志。
var lastScrollTop = 0;
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
window.addEventListener("scroll", function(){
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
// Do scroll down code
console.log("Down");
} else {
// Do scroll up code
console.log("Up");
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);
&#13;
div {
height: 300px;
border: 1px solid;
}
&#13;
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
&#13;
答案 1 :(得分:0)
这适用于我的场景(在全屏页面中检测鼠标滚轮)
// Detect IE version
var iev=0;
var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var rv=navigator.userAgent.indexOf("rv:11.0");
if (ieold) iev=new Number(RegExp.$1);
if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
if (trident&&rv!=-1) iev=11;
// Firefox or IE 11
if(typeof InstallTrigger !== 'undefined' || iev == 11) {
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('Up');
}
else if(st > lastScrollTop) {
console.log('Down');
}
lastScrollTop = st;
});
}
// Other browsers
else {
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('Up');
}
else if(e.originalEvent.wheelDelta < 0) {
console.log('Down');
}
});
}