获取窗口高度和宽度

本文介绍了如何使用JavaScript获取浏览器窗口的尺寸及位置的方法。首先尝试使用window.innerWidth和window.innerHeight获取窗口尺寸,若不可用,则根据浏览器兼容模式选择document.documentElement或document.body的相应属性。对于窗口位置,则通过screenLeft/screenTop或screenX/screenY属性获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们首先把window.innerWidth和window.innerHeight的值分别付给了pageWidth和pageHeight。

 

- 取得窗口大小的代码: 复制代码 代码如下:

var pageWidth = window.innerWidth, var pageHeight = window.innerHeight;

if(typeof pageWidth != "number"){ if(document.compatMode == "number"){ pageWidth = document.documentElement.clientWidth; pageHeight = document.documentElement.clientHeight; }else{ pageWidth = document.body.clientWidth; pageHeight = document.body.clientHeight; } }

我们首先把window.innerWidth和window.innerHeight的值分别付给了pageWidth和pageHeight。然后检查pageWidth中保存的是不是一个数值;如果不是,则通过document.compatMode来确定页面是否处于标准模式。如果是,则分别使用document.documentElement.clientWidth和document.documentElement.clientHeight的值。否则,就使用document.body.clientWidth和document.body.clientHeight的值。 取得窗口位置的代码: 复制代码 代码如下: var leftPos = (typeof window.screenLeft == "number") ? window.screenLeft : window.screenX; var topPos = (typeof window.screenTop == "number") ? window.screenTop : window.screenY;   这两个例子目的是取得窗口左边和上边的位置,首先运用二元操作符判断screenLeft属性和screenTops属性是否存在,如果存在(在IE、Safari、Opera和Chrome中),则取这两个属性的值。如果不存在(在Firefox中),则取screenX和screenY的值。

转载于:https://www.cnblogs.com/keethebest/p/3554126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值