html可视区高度,你真的懂js获取可视区宽高吗

原生js获取高度不就是就window.innerHeight一句话的事,可是真的这么简单吗

来看个测试页面,如果页面带有横向纵向的滚动条,我们打印出各个高度进行查看对比

顺便你也可以看看document.body和document.documentElement在各个浏览器的差异;document.documentElement返回的是整个文档的根节点即 html 标签;document.body 返回的是DOM对象里的body子节点,即 body 标签

console.log('document.documentElement.clientHeight-' + document.documentElement.clientHeight);

console.log('document.documentElement.scrollHeight-' + document.documentElement.scrollHeight);

console.log('document.documentElement.offsetHeight-' + document.documentElement.offsetHeight);

console.log('document.body.clientHeight-' + document.body.clientHeight);

console.log('document.body.scrollHeight-' + document.body.scrollHeight);

console.log('document.body.offsetHeight-' + document.body.offsetHeight);

console.log('window.innerHeight-' + window.innerHeight);

复制代码

ie8下各个值

12832b0286d79728a245489acaf8a7df.png

ie9下各个值

a6b2e508aef11f16f475ef412d50d87f.png

ie10跟ie9一样不列图了

ie11下各个值

763790a93772a265145c20267e7522d9.png 6. 火狐浏览器下各个值

b89305e8e99daaa0e7b573260d08c731.png

chorme浏览器下各个值

111eb81f1c7e5832d2c0acd7a20ea9f9.png

通过以上各图对比不难看出(先排除ie8)

window.innerHeight = document.documentElement.clientHeight + 滚动条高度;

如果没有滚动条则window.innerHeight = document.documentElement.clientHeight

在来说说ie8

ie8比较特殊不支持window.innerHeight并且html还自带有2像素的边框; 可以通过document.documentElement.offsetHeight - 2 * 2得到window.innerHeight的值

所以ie8的window.innerHeight = document.documentElement.offsetHeight - 2 * 2 = document.documentElement.clientHeight + 滚动条高度。

如果没有滚动条window.innerHeight = document.documentElement.offsetHeight - 2 * 2 = document.documentElement.clientHeight

所以获取可视区的高度不是简单的window.innerHeight,真正的可视区高度不应该包括滚动条

/**

* 获取视口宽高 兼容兼容到ie8

* @param {boolean} flag 标识返回的宽高是否包含滚动条

* @return {object} {widht: xxx, height: xxx} 视口宽高

/

function getViewPort (flag) {

if (typeof flag === 'undefined') {

return {

width: document.documentElement.clientWidth,

height: document.documentElement.clientHeight

};

}

if (flag === true) {

// ie8 html 有2像素边框 上下, 左右 4像素

return {

width: window.innerWidth || document.documentElement.offsetWidth - 2 * 2,

height: window.innerHeight || document.documentElement.offsetHeight - 2 * 2

};

}

}

复制代码

获取文档的宽高呢

通过以上各图的对比,整个文档的高度,可以通过document.documentElement.scrollHeight来获取各个浏览器都比较一致,你也不必纠结到底是用document.body 还是用document.documentElement; 用clientHeight还是offsetHeight

/**

* 获取文档宽高 兼容兼容到ie8

*

* @return {object} {widht: xxx, height: xxx} 视口宽高

/

function getDocumentPort (flag) {

return {

width: document.documentElement.scrollWidth,

height: document.documentElement.scrollHeight

};

}

复制代码

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值