Capturing the “scroll down” event?

后端 未结 10 2077
闹比i
闹比i 2020-12-28 12:17

I\'m designing a very simple web page (HTML only), the only \"feature\" I want to implement is to do something when the user scrolls down the page, is there a way to capture

相关标签:
10条回答
  • 2020-12-28 12:53

    above answers are correct. Here's the vanilla Javascript approach.

    document.addEventListener("mousewheel", function(event){
      if(event.wheelDelta >= 0){
        console.log("up")
      }else{
        console.log("down")
      }
    })
    
    
    0 讨论(0)
  • 2020-12-28 12:54

    Just for completeness, there's another solution using another JS framework (Mootools)

    window.addEvent('scroll',function(e) {
        //do stuff
    });
    
    0 讨论(0)
  • 2020-12-28 12:56

    A better way is to not only check for scroll events but also for direction scrolling like below;

    $(window).bind('mousewheel', function(event) {
    if (event.originalEvent.wheelDelta >= 0) {
        console.log('Scroll up');
    }
    else {
        console.log('Scroll down');
    }
    });
    
    0 讨论(0)
  • 2020-12-28 12:56

    You can't do it with just HTML, you'll need to use Javascript. I recommend using jQuery, so your solution can look like this:

    $(document).ready(function() {
        $(window).scroll(function() {
          // do whatever you need here.
        });
    });
    

    If you don't want or are unable to use jQuery, you can use the onscroll solution posted by Anthony.

    0 讨论(0)
  • 2020-12-28 12:57

    This works for me.

    var previousPosition
    
    $(window).scroll(function(){
      var currentScrollPosition=$(window).scrollTop() + $(window).height()
      if (currentScrollPosition>previousScrollPosition) {
        console.log('down')
      }else if(currentScrollPosition<previousScrollPosition){
        console.log('up')
      }
      previousScrollPosition=currentScrollPosition
    });
    
    0 讨论(0)
  • 2020-12-28 12:59

    u can simply use this

    window.addEvent('scroll',function(e) {
        if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
                // enter code here
            }
    });
    
    0 讨论(0)
提交回复
热议问题