Woo*_*ody 119 javascript jquery scroll
我只想要一些简单的JQ/JS来检查当前页面/窗口(不是特定元素)是否有垂直滚动条.
谷歌搜索给了我这些基本功能似乎过于复杂的东西.
如何才能做到这一点?
Thi*_*lem 94
$(document).ready(function() {
// Check if body height is higher than window height :)
if ($("body").height() > $(window).height()) {
alert("Vertical Scrollbar! D:");
}
// Check if body width is higher than window width :)
if ($("body").width() > $(window).width()) {
alert("Horizontal Scrollbar! D:<");
}
});
Run Code Online (Sandbox Code Playgroud)
And*_*y E 74
试试这个:
var hasVScroll = document.body.scrollHeight > document.body.clientHeight;
Run Code Online (Sandbox Code Playgroud)
这只会告诉您垂直scrollHeight是否大于可查看内容的高度.该hasVScroll
变量将包含true或false.
如果您需要进行更彻底的检查,请将以下代码添加到上面的代码中:
// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");
// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible"
|| cStyle.overflowY == "visible"
|| (hasVScroll && cStyle.overflow == "auto")
|| (hasVScroll && cStyle.overflowY == "auto");
Run Code Online (Sandbox Code Playgroud)
Bha*_*rat 41
我尝试了以前的答案,似乎没有工作$("body").height()不一定代表整个html高度.
我更正了解决方案如下:
// Check if body height is higher than window height :)
if ($(document).height() > $(window).height()) {
alert("Vertical Scrollbar! D:");
}
// Check if body width is higher than window width :)
if ($(document).width() > $(window).width()) {
alert("Horizontal Scrollbar! D:<");
}
Run Code Online (Sandbox Code Playgroud)
has*_*nge 16
让我们从死里复活这个问题;)谷歌没有给你一个简单的解决方案是有原因的.特殊情况和浏览器怪癖会影响计算,并不像看起来那么简单.
不幸的是,到目前为止,这里列出的解决方案存在问题.我并不是要贬低它们 - 它们是很好的起点,可以触及更强大的方法所需的所有关键属性.但我不建议从任何其他答案中复制和粘贴代码,因为
$( document ).width()
并.height()
成为jQuery错误检测文档大小的牺牲品.window.innerWidth
,如果浏览器支持它,会使您的代码无法检测移动浏览器中的滚动条,其中滚动条的宽度通常为0.它们只是暂时显示为叠加层而不占用文档中的空间.放大手机也成为一个问题(长篇故事).html
和body
元素的溢出设置为非默认值时,可以抛弃检测(然后发生的事情有点涉及 - 参见此描述).我花了更多的时间来寻找一个"正常工作"(咳嗽)的解决方案.我提出的算法现在是一个插件jQuery.isInView的一部分,它暴露了一个.hasScrollbar
方法.如果您愿意,请查看来源.
在您完全控制页面而不必处理未知CSS的情况下,使用插件可能过度 - 毕竟,您知道哪些边缘情况适用,哪些不适用.但是,如果您在未知环境中需要可靠的结果,那么我认为这里概述的解决方案就不够了.你最好使用经过良好测试的插件 - 我的或任何人.
Kee*_*ker 15
这个对我有用:
function hasVerticalScroll(node){
if(node == undefined){
if(window.innerHeight){
return document.body.offsetHeight> window.innerHeight;
}
else {
return document.documentElement.scrollHeight >
document.documentElement.offsetHeight ||
document.body.scrollHeight>document.body.offsetHeight;
}
}
else {
return node.scrollHeight> node.offsetHeight;
}
}
Run Code Online (Sandbox Code Playgroud)
对于身体,只需使用hasVerticalScroll()
.
小智 11
var hasScrollbar = window.innerWidth > document.documentElement.clientWidth;
Run Code Online (Sandbox Code Playgroud)