0

我有一段 jQuery 代码 - 理论上 - 根据 URL 标记 (myaddress.html#wheretoscroll) 中散列后的内容,它向下滚动到窗口的特定部分。

调用的代码是这样的:

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

问题是文档滚动到一个完全偏离其预期对齐的位置。它几乎在右上角附近有锚点,但随着文档向下滚动,不准确性似乎越来越低。

然而...

如果我在 .click 或 .hover 函数中运行相同的代码,例如:

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

它滚动到它应该在的确切位置。我假设这是在 .ready 时未正确读取 DOM 的某种问题?任何更正此问题的建议(或在页面加载后立即触发操作但直接通过 .ready 的更优雅的方式)将不胜感激。

如果重要的话,我正在使用的 .scrollTo 插件可以在这里找到:http: //flesler.blogspot.com/2007/10/jqueryscrollto.html

干杯...

4

1 回答 1

2

试试这个:

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

在 DOM 准备好后,您的部分页面会继续加载。$(window).load()加载所有内容时触发 - 包括图像。

于 2010-10-28T17:32:28.923 回答