JavaScript 获取元素的尺寸

416 阅读1分钟

 获取视口的尺寸

// IE8 不兼容
window.innerWidth / window.innerHeight

// IE8 以下 标准模式 document.compatMode == "CSS1Compat"
document.documentElement.clientWidth 
document.documentElement.clientHeight

// IE8 以下 怪异模式 document.compatMode == "BackCompat"
document.body.clientWidth 
document.body.clientHeight

元素的几何尺寸 

div.getBoundingClientRect()  // 返回的是对象,border盒子宽高


div.scrollWidth / div.scrollHeight  // 1 元素内容的宽/高度,包括溢出的不可见内容

div.offsetWidth / div.offsetHeight  // 2 返回的是数字,border盒子宽高

div.clientWidth / div.clientHeight  // 3 返回的是数字,padding盒子宽高,不含滚动条

div.offsetLeft / div.offsetTop  // 对于无定位祖先元素,相对于文档的坐标;对于有定位的祖先元素,相对于最近有定位的祖先元素坐标

获取样式

dom.style //  获取行内样式 可读,可写 CSSStyleDeclaration

window.getComputedStyle(dom, null) // 只读,IE8 IE8以下不兼容 获取显示属性 CSSStyleDeclaration

dom.currentStyle  // IE8 IE8以下 使用

查看滚动条的距离

// IE8 以及 IE8以下不兼容
window.pageXOffset/window.pageYOffset  

window.scrollX/window.scrollY

// 兼容写法
document.body.scrollLeft + document.documentElement.scrollLeft
document.body.scrollTop + document.documentElement.scrollTop

滚动条滚动

window上的三个方法

scroll(0, 100) / scrollTo(0, 100)
scrollBy(0, 100)  // 增量