2

I know how to get the scrollTop of a page, I use this simple JS function (code copied around):

function GetScrolledTop() 
{
   //I never work in IE quirkmode, I always use DOCTYPE as 1st line, so I don't need to test for document.body.scrollTop
   return self['pageYOffset'] || document.documentElement.scrollTop; 
}

This works and my problem is the following: I tried to add it in the page onload event

<body onload="alert(GetScrolledTop());">

On page load I get ZERO (which make sense), but the problem is that I get ZERO even if I scroll the page and then reload it without touching the scrollbar.

It seems like the browser does:

  1. loads page
  2. calls my GetScrolledTop() (so obviously shows ZERO)
  3. then scrolls the page to where it was before.

Do you know how to get the scolledTop after the step 3? I mean how to get the scrolledTop AFTER the browser scrolled the page? (maybe without using a timer)

4

1 回答 1

2

可能不是不使用计时器。但是您也许可以使用延迟为 0 毫秒的计时器,它会在线程空闲时执行该函数,同时看起来仍然是即时的:

<body onload="window.setTimeout(function () { alert(GetScrolledTop()); } , 0);">

编辑- 认为可能还值得一提的是,大多数浏览器都支持该onscroll事件,该事件应该在窗口滚动后触发。

于 2010-03-29T18:29:38.643 回答