测试页面是否具有水平滚动条(计算机和移动设备) [英] Test if page has a horizontal scrollbar (computer & mobile devices)
问题描述
在网页上,我需要测试是否有水平滚动条(以便以编程方式更改某些其他元素的css).有什么方法可以使用jquery(或纯JavaScript)获取该信息?
On a web page, I need to test if there is a horizontal scrollbar or not (so that I programmatically change the css of some other element). Is there some way to get that information using jquery (or pure javascript)?
我测试过
function isHorizontalScrollbarEnabled() {
return $(document).width()!=$(window).width();
}
,但它似乎不适用于所有浏览器(例如,不适用于我测试过的最新三星手机).我需要它与所有浏览器一起使用,包括最近的移动设备.
but it does not seem to work with all browsers (does not work for example with a recent Samsung phone I tested). I need it to work with all browsers, including recent mobile devices.
谢谢!
编辑1
我测试了plalx和laconbass提供的解决方案,测试了IE8,Firefox,Chrome和iPad.可与IE,Firefox和amp; Chrome,但不是我想要的iPad.
I tested the solutions provided by plalx and laconbass, tested IE8, Firefox, Chrome and iPad. Works with IE, Firefox & Chrome but not as I want on the iPad.
问题似乎与移动设备上的缩放功能有关:即使在iPad上放大时,也会出现水平滚动条,document
,window
和document.body
的宽度不会改变(也是我今天早些时候测试过的三星手机也有同样的问题.
The problem seems related to the zooming feature on mobile devices: even though, when I zoom in on the iPad, a horizontal scrollbar appears, document
, window
and document.body
widths do not change (was also the same problem with the Samsung phone I tested earlier today).
这是我用来测试的代码:
Here is the code I used to test:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<title>test</title>
</head>
<body>
<div style="width: 500px; background: red;" id="test">click here to test</div>
<script type="text/javascript">
var i = 1;
$("#test").click(function(){
$(this).html("Test #" + (i++)
+ "<br>document width=" + $(document).width() + ", windows width=" + $(window).width()
+ "<br>document width=" + $(document).width() + ", body width=" + $(document.body).width()
);
});
</script>
</body>
</html>
有什么想法如何检测水平滚动条的存在,该滚动条在iPad等移动设备上放大/缩小后也可以工作?
Any idea how to detect the presence of a horizontal scrollbar that also works after zooming in/out on a mobile device like iPad?
推荐答案
//scrol 1px to the left
$(document).scrollLeft(1);
if($(document).scrollLeft() != 0){
//there's a scroll bar
}else{
//there's no scrollbar
}
//scroll back to original location
$(document).scrollLeft(0);
之所以可行,是因为如果没有滚动条,JQuery将无法滚动屏幕
This works because JQuery won't be able to scroll the screen if no scrollbar is available
这篇关于测试页面是否具有水平滚动条(计算机和移动设备)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!