当url包含锚点时,获取网页页面滚动条的垂直位置

我正在使用jQuery的scrollTop()方法来获取pageload上滚动条的垂直位置。 我需要在执行url中的锚点后获取此值(例如:www.domainname.com#foo)。 我可以使用以下代码,它适用于Firefox和IE:

ex url:www.domainname.com#foo

$(document).ready(function() { if ($(this).scrollTop() > 0) { // then a conditional statement based on the scrollTop() value if ($(this).scrollTop() > $("#sidenav").height()) { ... 

但是在Safari和Chrome中,document.ready()似乎在锚点之前执行,因此在此场景中,scrollTop()在页面加载时返回0。 在Chrome和Safari中执行锚点后,如何在页面加载时访问scrollTop()值?

您可能只想像setTimeout一样做一些快速和肮脏的事情,因为从Chrome或Safari可靠地获取它需要很多毫秒

 var MAX_CHECKS = 5; // adjust these values var WAIT_IN_MILLISECONDS = 100; // however works best var checks = 0; function checkScroll() { if ($(this).scrollTop() > 0) { // then a conditional statement based on the scrollTop() value if ($(this).scrollTop() > $("#sidenav").height()) { ... } } else { if (++checks < MAX_CHECKS) { // just to make sure, you can try again setTimeout(checkScroll, WAIT_IN_MILLISECONDS); } } } $(document).ready(function() { // You can also throw in an if statement here to exclude // URLs without # signs, single out WebKit browsers, etc. setTimeout(checkScroll, WAIT_IN_MILLISECONDS); ... }); 

请注意,您也可以使用if ($.browser.webkit) ,虽然此function已弃用,可能会移动到插件而不是主jQuery(支持function检测)。