Detect if a scroll event is triggered manually in jQuery

后端 未结 7 1084
执念已碎
执念已碎 2021-01-11 13:21

This question was already asked here a long time ago:

Detect jquery event trigger by user or call by code

But it has never been answered conclusively (or m

7条回答
  •  一向
    一向 (楼主)
    2021-01-11 13:27

    Using @Tony's accepted answer and @DanielTonon's comment I came up with the following solution:

      var animatedScroll = false;
      var lastAnimatedScroll = false;
      $(window).scroll(function(event){
        lastAnimatedScroll = animatedScroll;
        animatedScroll = $('html, body').is(':animated');
      });
    

    This seems to solve the issue mentioned whereby jquery removes the .is(':animated') then scrolls one more pixel, which leads to .is(':animated') ending on a false. By storing the second to last version of .is(':animated') you can be (more) sure whether or not the scroll was an animated one or not.

    When you want to know if the scroll was animated or not just check the lastAnimatedScroll variable.

    This has NOT been thoroughly tested by me but has been correct on many page refreshes so I will assume it works well enough.

提交回复
热议问题