문제

When I want to scroll a website by javascript code what is the corrent element to set the .scrollTop property on?

Is it window, document, document.body or html element?

Does jQuery have some trick to detect the intention to scroll the main viewport and unify the calls? It seems to me that sometimes $(window).scroolTop(value) works, but sometimes it doesn't.

도움이 되었습니까?

해결책

Normally, the <html> element, aka document.documentElement. However if you are using Quirks Mode, <body> (document.body) represents the viewport instead. (HTML/CSS doesn't explicitly state/require this, but it is how all modern browsers work.)

You don't ever want to be in Quirks Mode, but if you're writing a script for inclusion on other people's pages you will have to deal with it:

var viewport= document.compatMode==='BackCompat'? document.body : document.documentElement;
// do something with viewport.scrollTop

jQuery uses window.scrollTo() instead of setting the scroll properties directly. Either way is pretty much the same in practice. You could argue that using scrollTo is a bit cleaner in that it avoids relying on the viewport being represented by a particular element, but then jQuery still has to use scrollTop/scrollLeft to read the current value of the ‘other’ property anyway, so no big win. You can use pageXOffset/pageYOffset to read the current scroll position without relying on a particular element, but it's not supported everywhere so you still have to fallback to the scrollTop method.

Sadly none of these properties/methods have been standardised in the past. CSSOM Views finally address this.

다른 팁

There's a rider to bobince's answer, which is that Webkit browsers incorrectly set documentElement.scrollTop to zero regardless of whether you are in quirks or standards mode; therefore, you cannot completely rely on his one-liner.

https://bugs.webkit.org/show_bug.cgi?id=9248

http://code.google.com/p/chromium/issues/detail?id=2891

Someone with sufficient privileges should make this a comment to bobince's answer so that it is not missed, and I can then delete this post.

Depends on what you are scrolling, document/Window or a division

I had this problem before as well, and it behaved quite differently in a number of browsers. I ended up using this rather horrible piece of code:

function scrollToTop() {
    $('body, html').scrollTop(0);

    if ($.browser.webkit || $.browser.safari) {
        // Hack for webkit browsers: hide and show canvas layer so window will scroll up.
        // (scrollTop does not work right).
        $('#canvas').hide();
        window.setTimeout(function () {
            $('#canvas').show();
        }, 0);
    }
}

However, I only needed to scroll to the top, which is easier. I'm not sure how you would do this if you want to scroll to a specific point. Maybe use anchors?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top