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

可能你会以为获取可视区宽高不是很简单吗

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

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

顺便你也能够看看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);
复制代码
  1. ie8下各个值

image

  1. ie9下各个值

image

  1. ie10跟ie9同样不列图了
  2. ie11下各个值

image
6. 火狐浏览器下各个值

image

  1. chorme浏览器下各个值

image

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

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

若是没有滚动条则window.innerHeight = document.documentElement.clientHeightui

在来讲说ie8

ie8比较特殊不支持window.innerHeight而且html还自带有2像素的边框; 能够经过document.documentElement.offsetHeight - 2 * 2获得window.innerHeight的值spa

因此ie8的window.innerHeight = document.documentElement.offsetHeight - 2 * 2 = document.documentElement.clientHeight + 滚动条高度。3d

若是没有滚动条window.innerHeight = document.documentElement.offsetHeight - 2 * 2 = document.documentElement.clientHeightcode

因此获取可视区的高度不是简单的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仍是offsetHeightorm

/** * 获取文档宽高 兼容兼容到ie8 * * @return {object} {widht: xxx, height: xxx} 视口宽高 / function getDocumentPort (flag) { return { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight }; } 复制代码
相关文章
相关标签/搜索