你真的懂js获取可视区宽高吗
可能你會(huì)覺(jué)得獲取可視區(qū)寬高不是很簡(jiǎn)單嗎
原生js獲取高度不就是就window.innerHeight一句話的事,可是真的這么簡(jiǎn)單嗎
來(lái)看個(gè)測(cè)試頁(yè)面,如果頁(yè)面帶有橫向縱向的滾動(dòng)條,我們打印出各個(gè)高度進(jìn)行查看對(duì)比
順便你也可以看看document.body和document.documentElement在各個(gè)瀏覽器的差異;document.documentElement返回的是整個(gè)文檔的根節(jié)點(diǎn)即 html標(biāo)簽;document.body 返回的是DOM對(duì)象里的body子節(jié)點(diǎn),即 body 標(biāo)簽
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);通過(guò)以上各圖對(duì)比不難看出(先排除ie8)
window.innerHeight = document.documentElement.clientHeight 滾動(dòng)條高度;
如果沒(méi)有滾動(dòng)條則window.innerHeight = document.documentElement.clientHeight
在來(lái)說(shuō)說(shuō)ie8
ie8比較特殊不支持window.innerHeight并且html還自帶有2像素的邊框; 可以通過(guò)document.documentElement.offsetHeight - 2 * 2得到window.innerHeight的值
所以ie8的window.innerHeight = document.documentElement.offsetHeight - 2 * 2 = document.documentElement.clientHeight 滾動(dòng)條高度。
如果沒(méi)有滾動(dòng)條window.innerHeight = document.documentElement.offsetHeight - 2 * 2 = document.documentElement.clientHeight
所以獲取可視區(qū)的高度不是簡(jiǎn)單的window.innerHeight,真正的可視區(qū)高度不應(yīng)該包括滾動(dòng)條
/** * 獲取視口寬高 兼容兼容到ie8 * @param {boolean} flag 標(biāo)識(shí)返回的寬高是否包含滾動(dòng)條 * @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};} }獲取文檔的寬高呢
通過(guò)以上各圖的對(duì)比,整個(gè)文檔的高度,可以通過(guò)document.documentElement.scrollHeight來(lái)獲取各個(gè)瀏覽器都比較一致,你也不必糾結(jié)到底是用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}; }總結(jié)
以上是生活随笔為你收集整理的你真的懂js获取可视区宽高吗的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: node.js中exports与modu
- 下一篇: Github Actions:再次改变软