Capturing the “scroll down” event?

2019-02-02 20:55发布

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 that "event" somehow?

6条回答
看我几分像从前
2楼-- · 2019-02-02 21:15

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.

查看更多
▲ chillily
3楼-- · 2019-02-02 21:21

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
});
查看更多
The star\"
4楼-- · 2019-02-02 21:24

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');
}
});
查看更多
甜甜的少女心
5楼-- · 2019-02-02 21:29

u can simply use this

window.addEvent('scroll',function(e) {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
            // enter code here
        }
});
查看更多
走好不送
6楼-- · 2019-02-02 21:38

If you don't want to use jQuery (which you might not do for a very simple HTML page), you can accomplish this using regular Javascript:

<script>
function scrollFunction() {
    // do your stuff here;
}

window.onscroll = scrollFunction;
</script>

You mentioned that you wanted to do something when they scroll down the page - the onscroll event fires off scrolling in any direction, in either the x- or y-axis, so your function will be called any time they scroll.

If you really want it to only run your code when they scrolled down the page, you'd need to preserve the previous scroll position to compare against whenever onscroll gets called.

查看更多
Emotional °昔
7楼-- · 2019-02-02 21:41

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

window.addEvent('scroll',function(e) {
    //do stuff
});
查看更多
登录 后发表回答