元素尺寸和鼠标位置总结

元素宽高

element.offsetWidth/offsetHeight border-box(offsetHeight = padding + height + border = clientHeight + 滚动条 + 边框)

element.offsetLeft/offsetTop 相对于最近的祖先定位元素(CSS position 属性被设置为 relative、absolute 或 fixed 的元素)的偏移值

element.clientWidth/clientHeight padding-box(元素可视区域的高度,也就是说元素或窗口中可以看到内容的这个区域的高度,滚动条不算在内。clientHeight = topPadding + bottomPadding+ height - 水平滚动条高度)

element.clientLeft/clientTop padding + border厚度
element.scrollLeft/scrollTop 元素滚动像素大小,可读可写
element.scrollWidth/scrollHeight(ie9+) 元素的滚动宽和高,等于clientHeight + scrollTop + 下面隐藏的部分的高度,
由于元素内置滚动条在border内部,所以其等于padding-box + scrollLeft/top,

scrollHeight是元素的padding加元素内容的高度。这个高度与滚动条无关,是内容的实际高度。
计算方式 :scrollHeight = topPadding + bottomPadding + 内容margix box的高度。


element.getBoundingClientRect 视口坐标top,left,bottom,right,即border-box宽高(ie9+)width,height

元素content-box宽高

content-box = border-box - 厚度 = offsetWidth/offsetHeight(或者getBoundingClientRect计算得到) - clientLeft/clientTop

通过样式获取尺寸

window.getComputedStyle(元素,伪类)(ie9+) 伪类参数是必须的,不是伪类,设置为null,获取元素的实时样式
element.currentStyle(ie6-8) 等同于上者
getComputedStyle.getPropertyValue(ie9+) 取属性样式,根据css样式名,而不是驼峰
style.getAttribute()(ie6-8) 获取属性样式,使用驼峰
element.style 读写元素的行内样式,标签样式和外联样式无效

鼠标位置

event.clientX/clientY 鼠标视口坐标,相对于window,相对坐标
event.pageX/pageY(ie9+) 鼠标文档坐标,相对于document,绝对坐标

window尺寸

window.innerWidth/innerHeight(ie9+) 视口宽高,即window的宽高,不包括浏览器边框,但是报表滚动条的宽度/高度
window.pageXOffset/pageYOffset(ie9+) 页面滚动的像素值(所有浏览器表现一致,优先选用,而scrollLeft/scrollTop各个浏览器表现不一致)

视口尺寸(不包含滚动条)

width:  document.documentElement.clientWidth || document.body.clientWidth

height: document.documentElement.clientHeight || document.body.clientHeight

window滚动像素值兼容写法

scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;

元素视口坐标(相对window)

element.getBoundingClientRect()

得到 box = {top,left,right,bottom}

元素文档坐标(相对document),绝对坐标

绝对坐标 = 视口坐标 + 文档滚动距离 - 文档厚度

top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft

文档的厚度(padding+border)

clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;

posted @ 2016-12-30 11:46  全玉  阅读(260)  评论(0编辑  收藏  举报