如何使用jQuery获取没有滚动条的浏览器视口的高度和宽度?
这是我到目前为止尝试过的:
var viewportWidth = $("body").innerWidth();
var viewportHeight = $("body").innerHeight();
此解决方案不考虑浏览器滚动条。
发布于 2012-09-26 17:17:22
下面是一个通用的JS,它可以在大多数浏览器(FF,Cr,IE6+)中工作:
var viewportHeight;
var viewportWidth;
if (document.compatMode === 'BackCompat') {
viewportHeight = document.body.clientHeight;
viewportWidth = document.body.clientWidth;
} else {
viewportHeight = document.documentElement.clientHeight;
viewportWidth = document.documentElement.clientWidth;
}
发布于 2014-03-06 23:59:44
script $(window).height()
确实可以很好地工作(显示视口的高度,而不是滚动高度的文档),但它需要您在文档中正确放置doctype标记,例如以下doctype:
对于html5:<!doctype html>
对于过渡html4:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
可能某些浏览器假定的默认文档类型是这样的,即$(window).height()
接受文档的高度,而不是浏览器的高度。有了doctype规范,这个问题就得到了令人满意的解决,我敢肯定你们可以避免“将滚动溢出更改为隐藏然后再返回”的做法,很抱歉,这是一个有点肮脏的把戏,特别是如果您没有将其记录在代码中以供将来程序员使用的话。
此外,如果你正在编写脚本,你可以发明测试来帮助你的库中的程序员,让我来发明几个:
$(document).ready(function() {
if(typeof $=='undefined') {
alert("Error, you haven't called JQuery library");
}
if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
alert("ERROR, check your doctype, the calculated heights are not what you might expect");
}
});
发布于 2016-10-14 22:21:55
$(document).ready(function() {
//calculate the window height & add css properties for height 100%
wh = $( window ).height();
ww = $( window ).width();
$(".targeted-div").css({"height": wh, "width": ww});
});
https://stackoverflow.com/questions/8794338
复制相似问题