Javascript 检测滚动方向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31223341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:24:20  来源:igfitidea点击:

Detecting scroll direction

javascriptscrollonscroll

提问by dwinnbrown

So I am trying to use the JavaScript on scrollto call a function. But I wanted to know if I could detect the direction of the the scroll without using jQuery. If not then are there any workarounds?

所以我试图使用 JavaScripton scroll来调用一个函数。但我想知道是否可以在不使用 jQuery 的情况下检测滚动方向。如果没有,那么是否有任何解决方法?

I was thinking of just putting a 'to top' button but would like to avoid that if I could.

我想只放一个“顶部”按钮,但如果可以的话,我想避免这种情况。

I have now just tried using this code but it didn't work:

我现在刚刚尝试使用此代码,但没有用:

if document.body.scrollTop <= 0 {
    alert ("scrolling down")
} else {
    alert ("scrolling up")
}

回答by Prateek

It can be detected by storing the previous scrollTop value and comparing the current scrollTop value with it.

可以通过存储先前的 scrollTop 值并将当前的 scrollTop 值与其进行比较来检测它。

JS :

JS:

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.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
   var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
   if (st > lastScrollTop){
      // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);

回答by IT VLOG

Simple way to catch all scroll events (touch and wheel)

捕获所有滚动事件的简单方法(触摸和滚轮)

window.onscroll = function(e) {
  // print "false" if direction is down and "true" if up
  console.log(this.oldScroll > this.scrollY);
  this.oldScroll = this.scrollY;
}

回答by Vasi

Use this to find the scroll direction. This is only to find the direction of the Vertical Scroll. Supports all cross browsers.

使用它来查找滚动方向。这只是为了找到垂直卷轴的方向。支持所有跨浏览器。

var scrollableElement = document.body; //document.getElementById('scrollableElement');

scrollableElement.addEventListener('wheel', checkScrollDirection);

function checkScrollDirection(event) {
  if (checkScrollDirectionIsUp(event)) {
    console.log('UP');
  } else {
    console.log('Down');
  }
}

function checkScrollDirectionIsUp(event) {
  if (event.wheelDelta) {
    return event.wheelDelta > 0;
  }
  return event.deltaY < 0;
}

Example

例子

回答by davecar21

You can try doing this.

你可以试试这样做。

function scrollDetect(){
  var lastScroll = 0;

  window.onscroll = function() {
      let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value

      if (currentScroll > 0 && lastScroll <= currentScroll){
        lastScroll = currentScroll;
        document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";
      }else{
        lastScroll = currentScroll;
        document.getElementById("scrollLoc").innerHTML = "Scrolling UP";
      }
  };
}


scrollDetect();
html,body{
  height:100%;
  width:100%;
  margin:0;
  padding:0;
}

.cont{
  height:100%;
  width:100%;
}

.item{
  margin:0;
  padding:0;
  height:100%;
  width:100%;
  background: #ffad33;
}

.red{
  background: red;
}

p{
  position:fixed;
  font-size:25px;
  top:5%;
  left:5%;
}
<div class="cont">
  <div class="item"></div>
  <div class="item red"></div>
  <p id="scrollLoc">0</p>
</div>

回答by Emmanual

This is an addition to what prateek has answered.There seems to be a glitch in the code in IE so i decided to modify it a bit nothing fancy(just another condition)

这是对 prateek 已回答的内容的补充。 IE 中的代码似乎存在故障,因此我决定对其进行一些修改(只是另一种情况)

$('document').ready(function() {
var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       console.log("down")
   }
   else if(st == lastScrollTop)
   {
     //do nothing 
     //In IE this is an important condition because there seems to be some instances where the last scrollTop is equal to the new one
   }
   else {
      console.log("up")
   }
   lastScrollTop = st;
});});

回答by thewebHymanal

  1. Initialize an oldValue
  2. Get the newValue by listening to the event
  3. Subtract the two
  4. Conclude from the result
  5. Update oldValue with the newValue
  1. 初始化一个 oldValue
  2. 通过监听事件获取 newValue
  3. 两者相减
  4. 从结果中得出结论
  5. 用 newValue 更新 oldValue

// Initialization

// 初始化

let oldValue = 0;

//Listening on the event

//监听事件

window.addEventListener('scroll', function(e){

    // Get the new Value
    newValue = window.pageYOffset;

    //Subtract the two and conclude
    if(oldValue - newValue < 0){
        console.log("Up");
    } else if(oldValue - newValue > 0){
        console.log("Down");
    }

    // Update the old value
    oldValue = newValue;
});

回答by Igal S.

You can get the scrollbar position using document.documentElement.scrollTop. And then it is simply matter of comparing it to the previous position.

您可以使用 获取滚动条位置document.documentElement.scrollTop。然后只需将其与之前的位置进行比较即可。

回答by WagonWolf

I personally use this code to detect scroll direction in javascript... Just you have to define a variable to store lastscrollvalue and then use this if&else

我个人使用这段代码来检测 javascript 中的滚动方向......只是你必须定义一个变量来存储 lastscrollvalue 然后使用这个 if&else

let lastscrollvalue;

function headeronscroll() {

    // document on which scroll event will occur
    var a = document.querySelector('.refcontainer'); 

    if (lastscrollvalue == undefined) {

        lastscrollvalue = a.scrollTop;

        // sets lastscrollvalue
    } else if (a.scrollTop > lastscrollvalue) {

        // downscroll rules will be here
        lastscrollvalue = a.scrollTop;

    } else if (a.scrollTop < lastscrollvalue) {

        // upscroll rules will be here
        lastscrollvalue = a.scrollTop;

    }
}

回答by Usman Ahmed

This simple code would work: Check the console for results.

这个简单的代码可以工作:检查控制台以获取结果。

let scroll_position = 0;
let scroll_direction;

window.addEventListener('scroll', function(e){
    scroll_direction = (document.body.getBoundingClientRect()).top > scroll_position ? 'up' : 'down';
    scroll_position = (document.body.getBoundingClientRect()).top;
    console.log(scroll_direction);
});