Make “scrollLeft” / “scrollTop” changes not trigger scroll event listener

前端 未结 5 653
刺人心
刺人心 2020-11-30 10:02

Currently my program is in a spot where it both listens for the user to scroll a certain element, but also, at times, automatically scrolls this element by itself. (Not a gr

5条回答
  •  不知归路
    2020-11-30 10:31

    All right, my final solution, building off of Shog9 (not my real code, but my approach):

    var oldScrollLeft = element.scrollLeft;
    element.scrollLeft = x;
    if(element.scrollLeft != oldScrollLeft) {
      ignoreScrollEvents = true;
    }
    
    function onScroll() {
      if(!ignoreScrollEvents) performGreatActions();
      ignoreScrollEvents = false;
    }
    

    The if statement only sets the ignore flag when the scrollLeft value actually ends up changing, so cases like setting from 0 to 0 don't set the flag incorrectly.

    Thanks, all!

提交回复
热议问题