为什么scrollTop,pageYOffset和height都不起作用? [英] Why are scrollTop, pageYOffset, and height all not working?

查看:336
本文介绍了为什么scrollTop,pageYOffset和height都不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测浏览器窗口上是否有垂直滚动条(如果内容超过窗口高度并溢出).我已经尝试document.body.scrollTopwindow.pageYOffsetdocument.body.style.height ...  没有起作用了!

对变量进行window.alert测试使用这些属性初始化的pageYOffset始终返回 0 ,无论是否存在滚动条,而其他两个返回似乎是空字符串的字符串.

我唯一的想法可能是CSS定位冲突导致了这种情况,但似乎没有这种冲突... 任何想法,解决方案,解决方法吗?

I am trying to detect if there is a vertical scrollbar or not on the browser window (if the content exceeds the window height and overflows). I have tried document.body.scrollTop, window.pageYOffset, and document.body.style.height...  none of these are working!

Upon doing a window.alert test on variables initialized with these properties, pageYOffset always returns 0 no matter if there is a scrollbar or not, and the other two return what seems to be an empty String.

My only idea is that maybe CSS positioning conflicts are causing this, but there seem to be no such conflicts...  Any ideas, solutions, workarounds?

推荐答案

window.innerWidth - document.documentElement.clientWidth

返回浏览器窗口的垂直滚动条的宽度,如果没有滚动条,则返回0.

returns the width of the vertical scroll-bar of the browser-window, and 0 if there is no scroll-bar.

所以,您可以拥有一个功能...

So, you could have a function...

function windowHasVerticalScrollbar () {
    return window.innerWidth - document.documentElement.clientWidth > 0;
}

不幸的是,IE8和IE7不支持window.innerWidth值,因此该技术在那些浏览器中不起作用. (但是,它确实可以在IE9和所有其他浏览器中使用.)

Unfortunately, IE8 and IE7 don't support the window.innerWidth value, so this technique will not work in those browsers. (However, it does work in IE9 and all the other browsers).

此外,由于documentElement<html>元素(网页的根元素),因此,如果在该元素上设置样式(如边距,绝对定位等),则计算可能会返回错误结果.

Also, since the documentElement is the <html> element (the root element of the web-page), if you set styles on that element (like margins, absolute positioning, etc.), the calculation may return incorrect results.

这篇关于为什么scrollTop,pageYOffset和height都不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆