如何在页面 onload 事件之后获取页面的滚动顶部?
我知道如何获取页面的 scrollTop
,我使用这个简单的 JS 函数(代码复制过来):
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;
}
这有效,我的问题如下:我尝试将其添加到页面 onload 事件
<body onload="alert(GetScrolledTop());">
中页面加载我得到零(这是有道理的),但问题是我得到零即使我滚动页面然后重新加载它而不触摸滚动条。
浏览器似乎是这样做的:
- 加载页面
- 调用我的
GetScrolledTop()
(所以显然显示零), - 然后将页面滚动到之前的位置。
你知道如何在第3步之后获取scolledTop
吗? 我的意思是如何获得 scrolledTop
浏览器滚动页面后? (也许不使用计时器)
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:
- loads page
- calls my
GetScrolledTop()
(so obviously shows ZERO) - 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果不使用计时器,可能就不行。但是您也许可以使用延迟为 0 毫秒的计时器,该计时器将在线程空闲时执行该函数,同时仍然看起来是即时的:
编辑 - 认为还值得一提的是< a href="http://www.quirksmode.org/dom/events/index.html#t021" rel="nofollow noreferrer">大多数浏览器支持
onscroll
事件,该事件应在窗口滚动后触发。Probably not without using a timer. But you might be able to use a timer with a 0ms delay, which would execute the function when the thread becomes idle, whilst still appearing to be instant:
EDIT - Thought it might also be worth mentioning that most browsers support the
onscroll
event, which should fire after the window scrolls.