当网址包含锚点时,获取页面加载时网页滚动条的垂直位置 [英] Get vertical position of scrollbar for a webpage on pageload when the url contains an anchor

查看:88
本文介绍了当网址包含锚点时,获取页面加载时网页滚动条的垂直位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的scrollTop()方法来获取页面加载时滚动条的垂直位置.在执行网址中的锚点之后,我需要获取此值(例如,网址:www.domainname.com#foo).我可以使用以下代码,并且它可以在Firefox和IE中运行:

I am using jQuery's scrollTop() method to get the vertical position of the scroll bar on pageload. I need to get this value after the anchor in the url is executed (ex url: www.domainname.com#foo). I can use the following code and it works in Firefox and IE:

ex url:www.domainname.com#foo

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()值?

But in Safari and Chrome document.ready() seems to execute before the anchor so scrollTop() returns 0 on page load in this scenario. How can I access the scrollTop() value on page load after the anchor executes in Chrome and Safari?

推荐答案

您可能只想做像setTimeout这样的快捷操作,要花多毫秒才能可靠地从Chrome或Safari获得它

You might just want to do something quick-and-dirty like setTimeout for however many milliseconds it takes to get it from Chrome or Safari reliably

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),尽管该功能已被弃用,并且可能移至插件而不是主jQuery(有利于功能检测).

Note that you can also use if ($.browser.webkit), although this feature is deprecated and may be moved to a plugin instead of the main jQuery (in favor of feature detection).

这篇关于当网址包含锚点时,获取页面加载时网页滚动条的垂直位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆