Using window.onscroll event to detect page/frame scrolling

允我心安 提交于 2019-12-01 00:35:32

If you read about the clunkiness in WebKit on Quirksmode, you'll notice the following:

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.

This issue shouldn't affect what you're trying to achieve since you're not setting the scrollTop of any element. You're attaching onscroll to the window, which appears to have no issues between any browser anyway.

Here's another alternative method you could try. I use it to position a toolbar div on top of the page (works for ipad too).

Instead of using the onScroll event, I am using a timer to fire every 500ms to detect where the windows is scrolled to via scrollTop . You could adjust the timer to about 200ms if you like.

Here's a stripped down sample of my code:

This jquery code checks when and if my dom element div named "floatlayer" (which is a div that contains my buttons toolbar) is ready and then calls the function setRepeater

$(#floatlayer").ready(function () {
    return setRepeater();
});

Then, this is the function that creates a timer to keep executing the function "keepIncrease" every 500ms

 function setRepeater() {
        aTimer = window.setInterval("keepIncrease()", 500);
        return false;
    }

This is the function keepIncrease() which is repeated every 500ms and is responsible to position the toolbar div based on the current window scrolled position :

function keepIncrease() {
    var divToolbar = $("#floatlayer")[0];

    var currentPos =  $(window).scrollTop();
    divToolbar.style.top = currentPos + "px";

    return false;
}

Something else out of topic: If your content is inside an iframe, you could also use $(window.parent).scrollTop() instead of $(window).scrollTop()

Why not just use "fixed"?

Oh, I see, I missed the part about the header.

You could still utilize the position:fixed option, though. You would just set the position against "body" initially (accounting for the 75px gap), and once the header leaves viewability, you can realign the div against the top of the viewport. But without using onscroll in some way or another you probably won't be able to do what you want to do. Sometimes you just have to make the decision: Do I want the feature more, or the people more?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!