javascript – 使用window.onscroll事件来检测页面/框架滚动

我想在页面内放置一个DIV,即使用户垂直滚动页面,它也能被用户看到.

页面顶部有一个标题,高度为75像素.现在,当用户位于页面顶部并且未垂直滚动时,必须在标题下方提出DIV.但是,一旦用户滚动页面导致标题不在视线范围内,相同的DIV现在必须位于页面顶部(即靠近浏览器视口的顶部边缘)

我最担心的是在浏览器上支持window.onscroll事件.我检查了QuirksMode的兼容性(http://www.quirksmode.org/dom/events/scroll.html).它似乎在IE和Firefox上具有良好的兼容性.然而,Safari和Chrome的支持似乎有点古怪.这两种浏览器都是我目标浏览器列表的一部分.

有人能告诉我window.onscroll事件是否是检测页面/框架滚动的有效方法?还有其他建议吗?

附:我考虑过使用CSS位置:固定规则.它接近解决方案,但DIV只是停留在一个位置,我无法根据标题的可见性自适应地移动.

谢谢!

解决方法:

如果您在Quirksmode上阅读WebKit中的笨拙,您会注意到以下内容:

Safari (but not on iPhone) and Chrome seem to monitor scrollTop acces in order to determine whether the user has scrolled an element. The log function of my test script changes scrollTop regularly, and Safari responds by firing a scroll event. Since the logging of this event changes the log element’s scrollTop once more, scroll events will be fired continuously.
All this happens when the log element at the bottom of the page doesn’t have a scrollbar yet, when it has a normal overflow: visible, and even when I set scrollTop to 0 each time a new event is logged. The buggy behaviour stops only when I remove the scrollTop line entirely.

由于您没有设置任何元素的scrollTop,因此该问题不应影响您要实现的目标.您将onscroll附加到窗口,无论如何,这似乎在任何浏览器之间都没有问题.

上一篇:tp6 加 微信小程序获取opendid (附带源代码)


下一篇:Demo_敌军坦克生成,坦克移动(可以拓展发射子弹,敌军消失获取分数或者添加动画,声音功能)