简体   繁体   中英

javascript scroll event inconsistency

I was trying to trigger a scroll event. And found out that this simple task is not so simple.

Using jQuery v1.9.1 Code

var win = $(window);
win.on("scroll", function(){
    console.log("running");
});
// trigger the scroll event
win.trigger("scroll"); //no success 

// change the scrollTop to +1
win.scrollTop(win.scrollTop()+1) //no success 

// change the scrollTop to -1
win.scrollTop(win.scrollTop()-1) //no success

// change the scrollTop to +2
win.scrollTop(win.scrollTop()+2) //fires twice

// change the scrollTop to +1.7
win.scrollTop(win.scrollTop()+1.7) //fires twice

Is there a correct reliable way to trigger a scroll event? See jsFiddle https://jsfiddle.net/u9dygoxf/1/

It looks like the scroll event is actually only triggered if you manually trigger it or the scrollTop() function actually scrolls the window.

This will always alert a value, although sometimes it's zero:

var win = $(window);
win.on('scroll', function() {
  alert('scrolled: ' + win.scrollTop());
});
win.trigger('scroll');

This will alert a value as long as the page is not already scrolled all the way to the bottom.

var win = $(window);
win.on('scroll', function() {
  alert('scrolled: ' + win.scrollTop());
});
win.scrollTop(win.scrollTop() + 1);

This will alert a value as long as the page is not already scrolled all the way to the top.

var win = $(window);
win.on('scroll', function() {
  alert('scrolled: ' + win.scrollTop());
});
win.scrollTop(win.scrollTop() - 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM