我有一段 jQuery 代码,理论上,它会根据 URL 标记中的哈希值后面的内容向下滚动到窗口的特定部分 (myaddress.html#wheretoscroll)。
调用的代码是这样的:
$(document).ready(function() {
anchor = unescape(self.document.location.hash.substring(1))
if (anchor) {
$.scrollTo('#anchor-' + anchor, 500, {offset:-150});
}
}
问题在于文档滚动到的位置偏离了预期的对齐方式。它几乎在右上角附近获得了 anchor ,但似乎向下滚动得太远,并且随着文档的下降,越来越不准确。
但是...
如果我在 .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
干杯...
最佳答案
试试这个:
$(window).load(function() {
anchor = unescape(self.document.location.hash.substring(1))
if (anchor) {
$.scrollTo('#anchor-' + anchor, 500, {offset:-150});
}
}
DOM 准备就绪后,页面的某些部分将继续加载。 $(window).load()
在加载所有内容(包括图像)时触发。
关于javascript - jQuery:方法通过 .click 可以正常工作,但直接从 document.ready 运行时则无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4045437/