我正在寻找达到这种效果的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
有任何想法吗?
wheel这几天最容易使用该事件:stackoverflow.com/a/33334461/3168107。
我正在寻找达到这种效果的东西:
$(window).scroll(function(event){
if (/* magic code*/ ){
// upscroll code
} else {
// downscroll code
}
});
有任何想法吗?
wheel这几天最容易使用该事件:stackoverflow.com/a/33334461/3168107。
Answers:
检查当前scrollTop与以前scrollTop
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st;
});
lastScrollTop0 开始还是将其正确初始化?
var lastScrollTop = $(window).scrollTop()在浏览器更新页面加载时的滚动位置后进行设置来解决。
您可以执行此操作而不必跟踪先前的滚动顶部,因为所有其他示例都需要:
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
我不是专家,因此可以随时进行进一步研究,但是当您使用时$(element).scroll,似乎正在监听的事件是“滚动”事件。
但是,如果您mousewheel使用绑定专门监听事件,则originalEvent回调的event参数的属性包含不同的信息。该信息的一部分是wheelDelta。如果为正,则将鼠标滚轮向上移动。如果为负,则将鼠标滚轮向下移动。
我的猜测是mousewheel,即使页面不滚动,鼠标滚轮转动也会触发事件。可能不会触发“滚动”事件的情况。如果需要,可以event.preventDefault()在回调的底部进行调用以防止页面滚动,从而可以将mousewheel事件用于页面滚动以外的其他功能,例如某种类型的缩放功能。
scrollTop也没有更新,所以我需要检测滚动。实际上,$(window).scroll()根本没有开火。
存储上一个滚动位置,然后查看新滚动位置是否大于或小于该滚动位置。
这是避免任何全局变量的方法(此处提供小提琴):
(function () {
var previousScroll = 0;
$(window).scroll(function(){
var currentScroll = $(this).scrollTop();
if (currentScroll > previousScroll){
alert('down');
} else {
alert('up');
}
previousScroll = currentScroll;
});
}()); //run this anonymous function immediately
这个帖子和其他答案可能有3个解决方案。
解决方案1
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('up 1');
}
else {
console.log('down 1');
}
lastScrollTop = st;
});
解决方案2
$('body').on('DOMMouseScroll', function(e){
if(e.originalEvent.detail < 0) {
console.log('up 2');
}
else {
console.log('down 2');
}
});
解决方案3
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('up 3');
}
else {
console.log('down 3');
}
});
我无法在Safari上进行测试
chrome 42(Win 7)
Firefox 37(Win 7)
IE 11(Win 8)
IE 10(Win 7)
IE 9(Win 7)
IE 8(Win 7)
我检查了IE 11和IE 8的副作用是否来自
if else声明。因此,我将其替换if else if为以下语句。
通过多浏览器测试,我决定将解决方案3用于常见的浏览器,将解决方案1用于firefox和IE 11。
我引用此答案来检测IE 11。
// 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');
}
});
}
Safari browser,这将有助于补充解决方案。
我了解已经有一个可以接受的答案,但想发布我正在使用的内容,以防它可以帮助任何人。我得到了cliphex与mousewheel事件类似的方向,但支持Firefox。如果您正在执行诸如锁定滚动之类的操作且无法获得当前滚动的顶部,则这样做很有用。
在此处查看实时版本。
$(window).on('mousewheel DOMMouseScroll', function (e) {
var direction = (function () {
var delta = (e.type === 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta);
return delta > 0 ? 0 : 1;
}());
if(direction === 1) {
// scroll down
}
if(direction === 0) {
// scroll up
}
});
在FF中,scroll事件的行为异常(由于平滑滚动,它被触发了很多次),但是它可以工作。
注:该滚动实际上事件被触发拖动滚动条时,使用光标键或鼠标滚轮。
//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
padding: "5px 7px",
background: "#e9e9e9",
position: "fixed",
bottom: "15px",
left: "35px"
});
//binds the "scroll" event
$(window).scroll(function (e) {
var target = e.currentTarget,
self = $(target),
scrollTop = window.pageYOffset || target.scrollTop,
lastScrollTop = self.data("lastScrollTop") || 0,
scrollHeight = target.scrollHeight || document.body.scrollHeight,
scrollText = "";
if (scrollTop > lastScrollTop) {
scrollText = "<b>scroll down</b>";
} else {
scrollText = "<b>scroll up</b>";
}
$("#test").html(scrollText +
"<br>innerHeight: " + self.innerHeight() +
"<br>scrollHeight: " + scrollHeight +
"<br>scrollTop: " + scrollTop +
"<br>lastScrollTop: " + lastScrollTop);
if (scrollHeight - scrollTop === self.innerHeight()) {
console.log("► End of scroll");
}
//saves the current scrollTop
self.data("lastScrollTop", scrollTop);
});
您也可以看看MDN,它提供了有关Wheel Event的重要信息。
注意:仅当使用鼠标滚轮时才会触发 wheel事件;光标键和拖动滚动条不会触发该事件。
我阅读了文档和示例:在浏览器中侦听此事件,
并在使用FF,IE,chrome,safari进行了一些测试之后,最终得到了以下代码片段:
//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
padding: "5px 7px",
background: "#e9e9e9",
position: "fixed",
bottom: "15px",
left: "15px"
});
//attach the "wheel" event if it is supported, otherwise "mousewheel" event is used
$("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) {
var evt = e.originalEvent || e;
//this is what really matters
var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel
scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari
scrollText = "";
if (deltaY > 0) {
scrollText = "<b>scroll down</b>";
} else {
scrollText = "<b>scroll up</b>";
}
//console.log("Event: ", evt);
$("#test").html(scrollText +
"<br>clientHeight: " + this.clientHeight +
"<br>scrollHeight: " + this.scrollHeight +
"<br>scrollTop: " + scrollTop +
"<br>deltaY: " + deltaY);
});
如果您只想知道是使用指针设备(鼠标还是触控板)向上或向下滚动,则可以使用事件的deltaY属性wheel。
$('.container').on('wheel', function(event) {
if (event.originalEvent.deltaY > 0) {
$('.result').append('Scrolled down!<br>');
} else {
$('.result').append('Scrolled up!<br>');
}
});
.container {
height: 200px;
width: 400px;
margin: 20px;
border: 1px solid black;
overflow-y: auto;
}
.content {
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="content">
Scroll me!
</div>
</div>
<div class="result">
<p>Action:</p>
</div>
var tempScrollTop, currentScrollTop = 0;
$(window).scroll(function(){
currentScrollTop = $("#div").scrollTop();
if (tempScrollTop > currentScrollTop ) {
// upscroll code
}
else if (tempScrollTop < currentScrollTop ){
// downscroll code
}
tempScrollTop = currentScrollTop;
}
我在这里看到了许多版本的好答案,但是似乎有些人遇到了跨浏览器问题,所以这是我的解决办法。
我已经成功地使用它来检测FF,IE和Chrome中的方向...由于我通常使用Windows,因此尚未在野生动物园中对其进行测试。
$("html, body").bind({'mousewheel DOMMouseScroll onmousewheel touchmove scroll':
function(e) {
if (e.target.id == 'el') return;
e.preventDefault();
e.stopPropagation();
//Determine Direction
if (e.originalEvent.wheelDelta && e.originalEvent.wheelDelta >= 0) {
//Up
alert("up");
} else if (e.originalEvent.detail && e.originalEvent.detail <= 0) {
//Up
alert("up");
} else {
//Down
alert("down");
}
}
});
请记住,我也可以使用它来停止任何滚动,因此,如果要继续滚动,则必须删除 e.preventDefault(); e.stopPropagation();
要忽略页面顶部和底部的任何突然/动量/反弹,以下是约西亚的公认答案的修改版本:
var prevScrollTop = 0;
$(window).scroll(function(event){
var scrollTop = $(this).scrollTop();
if ( scrollTop < 0 ) {
scrollTop = 0;
}
if ( scrollTop > $('body').height() - $(window).height() ) {
scrollTop = $('body').height() - $(window).height();
}
if (scrollTop >= prevScrollTop && scrollTop) {
// scrolling down
} else {
// scrolling up
}
prevScrollTop = scrollTop;
});
这段代码可以在IE,Firefox,Opera和Chrome上正常工作:
$(window).bind('wheel mousewheel', function(event) {
if (event.originalEvent.deltaY >= 0) {
console.log('Scroll down');
}
else {
console.log('Scroll up');
}
});
'wheel mousewheel '和属性deltaY必须在bind()函数中使用。
切记:出于安全原因,您是用户,必须更新其系统和浏览器。在2018年,“我有IE 7”的借口是胡说八道。我们必须教育用户。
祝你有美好的一天 :)
保持超级简单:
jQuery事件监听器方式:
$(window).on('wheel', function(){
whichDirection(event);
});
香草JavaScript事件监听器方式:
if(window.addEventListener){
addEventListener('wheel', whichDirection, false);
} else if (window.attachEvent) {
attachEvent('wheel', whichDirection, false);
}
功能保持不变:
function whichDirection(event){
console.log(event + ' WheelEvent has all kinds of good stuff to work with');
var scrollDirection = event.deltaY;
if(scrollDirection === 1){
console.log('meet me at the club, going down', scrollDirection);
} else if(scrollDirection === -1) {
console.log('Going up, on a tuesday', scrollDirection);
}
}
我写了一个更深入的职位上它在这里
您可以同时使用滚动和鼠标滚轮选项来跟踪上下移动。
$('body').bind('scroll mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('moving down');
}
else {
console.log('moving up');
}
});
您也可以用(窗口)替换'body'。
使用它来查找滚动方向。这只是找到垂直滚动的方向。支持所有跨浏览器。
var scrollableElement = document.getElementById('scrollableElement');
scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);
function findScrollDirectionOtherBrowsers(event){
var delta;
if (event.wheelDelta){
delta = event.wheelDelta;
}else{
delta = -1 * event.deltaY;
}
if (delta < 0){
console.log("DOWN");
}else if (delta > 0){
console.log("UP");
}
}
为什么没人使用滚动event返回的对象jQuery?
$window.on('scroll', function (event) {
console.group('Scroll');
console.info('Scroll event:', event);
console.info('Position:', this.pageYOffset);
console.info('Direction:', event.originalEvent.dir); // Here is the direction
console.groupEnd();
});
我正在使用chromium,但没有检查其他浏览器是否具有该dir属性。
由于v3 bind已弃用(“取代on”),wheel现在受支持,请忘记wheelDelta:
$(window).on('wheel', function(e) {
if (e.originalEvent.deltaY > 0) {
console.log('down');
} else {
console.log('up');
}
if (e.originalEvent.deltaX > 0) {
console.log('right');
} else {
console.log('left');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 style="white-space:nowrap;overflow:scroll">
🚂🚃🚃🚂🚃🚃🚃🚂🚃🚃🚂🚃🚃🚃🚂🚃<br/>
🚎🚌🚌🚌🚎🚌🚌🚎🚌🚌🚌🚎🚌🚌🚎🚌<br/>
🚂🚃🚃🚂🚃🚃🚃🚂🚃🚃🚂🚃🚃🚃🚂🚃<br/>
🚎🚌🚌🚌🚎🚌🚌🚎🚌🚌🚌🚎🚌🚌🚎🚌<br/>
🚂🚃🚃🚂🚃🚃🚃🚂🚃🚃🚂🚃🚃🚃🚂🚃<br/>
🚎🚌🚌🚌🚎🚌🚌🚎🚌🚌🚌🚎🚌🚌🚎🚌<br/>
</h1>
wheel事件在MDN上的浏览器兼容性(2019-03-18):
if(e.originalEvent.deltaY > 0) { console.log('down'); } else if(e.originalEvent.deltaY < 0) { console.log('up'); } else if(e.originalEvent.deltaX > 0) { console.log('right'); } else if(e.originalEvent.deltaX < 0) { console.log('left'); }
您也可以使用它
$(document).ready(function(){
var currentscroll_position = $(window).scrollTop();
$(window).on('scroll', function(){
Get_page_scroll_direction();
});
function Get_page_scroll_direction(){
var running_scroll_position = $(window).scrollTop();
if(running_scroll_position > currentscroll_position) {
$('.direction_value').text('Scrolling Down Scripts');
} else {
$('.direction_value').text('Scrolling Up Scripts');
}
currentscroll_position = running_scroll_position;
}
});
.direction_value{
position: fixed;
height: 30px;
background-color: #333;
color: #fff;
text-align: center;
z-index: 99;
left: 0;
top: 0;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="direction_value">
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
这是仅在用户端滚动时检测方向的最佳解决方案。
var currentScrollTop = 0 ;
$(window).bind('scroll', function () {
scrollTop = $(this).scrollTop();
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
if(scrollTop > currentScrollTop){
// downscroll code
$('.mfb-component--bl').addClass('mfbHide');
}else{
// upscroll code
$('.mfb-component--bl').removeClass('mfbHide');
}
currentScrollTop = scrollTop;
}, 250));
});
我有问题,有弹性滚动(滚动弹跳,橡皮条)。如果靠近页面顶部对我有用,则忽略向下滚动事件。
var position = $(window).scrollTop();
$(window).scroll(function () {
var scroll = $(window).scrollTop();
var downScroll = scroll > position;
var closeToTop = -120 < scroll && scroll < 120;
if (downScroll && !closeToTop) {
// scrolled down and not to close to top (to avoid Ipad elastic scroll-problems)
$('.top-container').slideUp('fast');
$('.main-header').addClass('padding-top');
} else {
// scrolled up
$('.top-container').slideDown('fast');
$('.main-header').removeClass('padding-top');
}
position = scroll;
});
这适用于所有PC或电话浏览器,扩展了最常见的答案。可以构建一个更复杂的事件对象window [“ scroll_evt”],然后在handleScroll()函数中对其进行调用。如果经过一定的延迟或传递了一定的增量以消除某些不必要的触发,则此触发将触发2个并发条件。
window["scroll_evt"]={"delta":0,"delay":0,"direction":0,"time":Date.now(),"pos":$(window).scrollTop(),"min_delta":120,"min_delay":10};
$(window).scroll(function() {
var currentScroll = $(this).scrollTop();
var currentTime = Date.now();
var boolRun=(window["scroll_evt"]["min_delay"]>0)?(Math.abs(currentTime - window["scroll_evt"]["time"])>window["scroll_evt"]["min_delay"]):false;
boolRun = boolRun && ((window["scroll_evt"]["min_delta"]>0)?(Math.abs(currentScroll - window["scroll_evt"]["pos"])>window["scroll_evt"]["min_delta"]):false);
if(boolRun){
window["scroll_evt"]["delta"] = currentScroll - window["scroll_evt"]["pos"];
window["scroll_evt"]["direction"] = window["scroll_evt"]["delta"]>0?'down':'up';
window["scroll_evt"]["delay"] =currentTime - window["scroll_evt"]["time"];//in milisecs!!!
window["scroll_evt"]["pos"] = currentScroll;
window["scroll_evt"]["time"] = currentTime;
handleScroll();
}
});
function handleScroll(){
event.stopPropagation();
//alert(window["scroll_evt"]["direction"]);
console.log(window["scroll_evt"]);
}