[英]javascript - How do i detect when a user is at the top of the webpage
I'm pretty much completely new to javascript, and I know there's already a similar question to this on here, but i would like the script as in. 我对javascript完全陌生,我知道这里已经存在与此类似的问题,但是我希望使用脚本。
if (user is at top of page) { (execute this function) } 如果(用户位于页面顶部){(执行此功能)}
Thanks in advance 提前致谢
This is a little snippet I use to determine the scrolltop of a page, I can't remember where I got it, or whether I wrote it myself so can't credit it. 这是我用来确定页面滚动条的一小段代码,我不记得我从哪里得到它,或者我是否自己写的所以不能相信它。
var st=0;
if(typeof pageYOffset!= 'undefined'){
//most browsers
st = pageYOffset;
} else {
var B = document.body; //IE 'quirks'
var D = document.documentElement; //IE with doctype
D = (D.clientHeight)? D: B;
st = D.scrollTop;
}
if st==0 then the user is at the top of the page! 如果st == 0,则用户位于页面顶部!
I'm using a function to make it cross-browser compatible that can be found here: Cross-browser method for detecting the scrollTop of the browser window 我正在使用一个使它与跨浏览器兼容的函数,可以在这里找到: 用于检测浏览器窗口的scrollTop的跨浏览器方法
function getScrollTop(){
if(typeof pageYOffset!= 'undefined'){
//most browsers
return pageYOffset;
}
else{
var B= document.body; //IE 'quirks'
var D= document.documentElement; //IE with doctype
D= (D.clientHeight)? D: B;
return D.scrollTop;
}
}
if(!getScrollTop()){
// user is at the top
}
Here is a little demo: http://jsfiddle.net/uDS4n/1/ 这是一个小演示: http : //jsfiddle.net/uDS4n/1/
Here's a clean solution that should make sense if you're new to JS: 如果您是JS新手,这是一个干净的解决方案,应该很有意义:
//call your function on scroll
window.onscroll = myScrollFunction;
function myScrollFunction(){
if(getYOffset() == 0){
//if at top, do this
alert('bingo');
}
};
//helper function (since ie handles scrolling different than firefox)
function getYOffset() {
var pageY;
if(typeof(window.pageYOffset)=='number') {
pageY=window.pageYOffset;
}
else {
pageY=document.documentElement.scrollTop;
}
return pageY;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.