开发者

Get vertical position of scrollbar for a webpage on pageload when the url contains an anchor

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

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

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 a开发者_运维技巧ccess the scrollTop() value on page load after the anchor executes in Chrome and 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);
  ...
});

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).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜