javascript 如何检测页面是否位于顶部?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7618721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I detect if the page is at the top?
提问by Akos
I want to make an event occur when the page scroll is at the top of the page.
Also I need an if
statement for it.
I am a beginner with javascript so any help is appreciated.
我想在页面滚动位于页面顶部时发生事件。我也需要一个if
声明。我是 javascript 的初学者,所以任何帮助表示赞赏。
I am looking for something like this:
我正在寻找这样的东西:
if (at_the_top_of_the_page) {
do_the_event_here
}
I think this is the right struckture for it. But I don't know what is the right code. I know that it will be in javascript. But I really don't know how...
我认为这是它的正确打击。但我不知道什么是正确的代码。我知道它将在 javascript 中。但是我真的不知道怎么...
回答by mowwwalker
Elements have a scrollTop
element that can be read or set. Make sure you're reading the correct element's scrollTop, the one that you're scrolling.
元素具有scrollTop
可以读取或设置的元素。确保您正在阅读正确元素的 scrollTop,即您正在滚动的那个。
ex:
前任:
var div = document.getElementById('scrollable');
if(div.scrollTop==0){
//Top of element
}
回答by Irfan
Get the position of the scrollbar using this
使用此获取滚动条的位置
function Getpostion(){
var vscroll = document.body.scrollTop;
alert(vscroll);
}
if vscroll is zero do your job. More details
如果 vscroll 为零,请完成您的工作。更多细节
回答by marc carreras
document.body.scrollTop === 0;
回答by Bala
To do the easy way: Include jquery library in your HTML document.
做一个简单的方法:在你的 HTML 文档中包含 jquery 库。
And to check if the user is on top of the page
并检查用户是否在页面顶部
var scrollPosition = $("body, html").scrollTop()
if (scrollPosition == 0){
// top of the page
}