Sea*_*ara 16 javascript scroll
有没有办法检查,使用JavaScript,如果页面是scroll(0,0)?
原因是我有一个整页滑块,我需要暂停第二页页面不在原点.
它可能不一定是因为页面正在滚动,因为我有内部HTML#链接,可以将页面加载到滚动点而不实际滚动.
因此,检查需要是页面不在顶部,而不是页面已滚动.
Esa*_*ija 34
试试这个:
document.body.scrollTop === 0
Run Code Online (Sandbox Code Playgroud)
更新了 2019 年的答案
document.body.scrollTop 已被弃用,并且在 Chrome 中根本无法使用。解决此问题的最佳方法是简单地查看所有三种可能性,以获得跨浏览器解决方案。
!window.pageYOffset
Run Code Online (Sandbox Code Playgroud)
这三个中的一个应该适用于所有浏览器类型。如果该值等于 0,则您位于视口的顶部。
您可以检查window.scrollY(窗口垂直滚动的像素数)是否等于0。如果要检查窗口是否已滚动到最左侧,则可以检查window.scrollX(窗口水平滚动的像素数)是否等于0。如果将两者结合起来,将确保窗口位于(0,0)位置。
if(window.scrollY==0){
//user scrolled to the top of the page
}
if(window.scrollX==0){
//user scrolled to the leftmost part of the page
}
if(window.scrollY==0&&window.scrollX==0){
//user scrolled to the leftmost part of the top of the page—i.e., they are at position (0, 0)
}
Run Code Online (Sandbox Code Playgroud)
演示:
if(window.scrollY==0){
//user scrolled to the top of the page
}
if(window.scrollX==0){
//user scrolled to the leftmost part of the page
}
if(window.scrollY==0&&window.scrollX==0){
//user scrolled to the leftmost part of the top of the page—i.e., they are at position (0, 0)
}
Run Code Online (Sandbox Code Playgroud)
html, body{
height: 3000px;
position: relative;
margin: 0;
}Run Code Online (Sandbox Code Playgroud)
为了更好地与浏览器兼容,请使用window.pageYOffset代替window.scrollY和window.pageXOffset代替window.scrollX。
在需要完全兼容浏览器的情况下(即IE <9),可以使用以下代码:
var x = (window.pageXOffset !== undefined)
? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body).scrollLeft;
//number of pixels scrolled horizontally (work with this value instead of window.scrollX or window.pageXOffset)
var y = (window.pageYOffset !== undefined)
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body).scrollTop;
//number of pixels scrolled vertically (work with this value instead of window.scrollY or window.pageYOffset)
Run Code Online (Sandbox Code Playgroud)