最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Determine what caused scroll event to fire up - Stack Overflow

programmeradmin5浏览0评论

It is known that scroll event could be fired up by using mouse-wheel, clicking on scrollbar arrows or dynamically with window.scrollTo(left, top) function.

Is it possible to determine what caused the scroll event to fire up? Whether it was user intervention or JS code?

It is known that scroll event could be fired up by using mouse-wheel, clicking on scrollbar arrows or dynamically with window.scrollTo(left, top) function.

Is it possible to determine what caused the scroll event to fire up? Whether it was user intervention or JS code?

Share Improve this question edited Jan 14, 2023 at 10:32 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 9, 2011 at 11:11 ritmasritmas 3651 gold badge4 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

I don't think you can determine what caused the scrolling. The scroll event only indicates that the window is scrolling, not why it's scrolling.

But perhaps you suspend the scroll event listener or set a flag before calling window.scrollTo() from your code. Here in Safari, if you use scrollTo(), the scroll event only fires once regardless of how much you scroll, so you could conceivably do something like this:

// somewhere in your code...
isCodedScrollEvent = true;
window.scrollTo(0, 200);

// elsewhere in your code...
function scrollListener(event) {
    if( isCodedScrollEvent ) {
         // event was caused by code, so handle it differently
         // and then flip the flag back to false, so the next
         // will be handled normally again
         isCodedScrollEvent = false;
    } else {
         // event was caused by user
    }
}

It ain't pretty, but it ought to work

发布评论

评论列表(0)

  1. 暂无评论