开发者

jQuery: method works correctly through .click, but not when run direct from document.ready

开发者 https://www.devze.com 2023-01-23 00:45 出处:网络
I have a piece of jQuery code which 开发者_如何学Python- in theory - scrolls down to a specific part of the window depending on what\'s after the hash in the URL tag (myaddress.html#wheretoscroll).

I have a piece of jQuery code which 开发者_如何学Python- in theory - scrolls down to a specific part of the window depending on what's after the hash in the URL tag (myaddress.html#wheretoscroll).

The code called is this:

$(document).ready(function() {
    anchor = unescape(self.document.location.hash.substring(1))
    if (anchor) {
        $.scrollTo('#anchor-' + anchor, 500, {offset:-150});
    }
}

The problem is that the document scrolls to a place well out of its intended alignment. It gets anchors near the top almost right, but seems to scroll too far down with increasing inaccuracy as the document goes down.

However...

If I run the same code inside a .click or .hover function, for example:

$(document).ready(function() {
    $('body').hover(function() {
        anchor = unescape(self.document.location.hash.substring(1))
        if (anchor) {
            $.scrollTo('#anchor-' + anchor, 500, {offset:-150});
        }
    });
});

it scrolls to the exact location it should be. I'm assuming this is some sort of problem with the DOM not being read correctly at the point of .ready? Any suggestions for correcting this (or a more elegant way of triggering the action as soon as the page loads but not directly through .ready) would be much appreciated.

If it matters, the .scrollTo plugin I'm using can be found here: http://flesler.blogspot.com/2007/10/jqueryscrollto.html

Cheers...


Try this instead:

$(window).load(function() {
    anchor = unescape(self.document.location.hash.substring(1))
    if (anchor) {
        $.scrollTo('#anchor-' + anchor, 500, {offset:-150});
    }
}

Parts of your page are continuing to load after the DOM is ready. $(window).load() fires when all your content is loaded -- including images.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号