元素坐标计算
窗口滚动条
1. 滚动条偏移量的计算
window.pageXOffset()
window.pageYOffset()
窗口坐标 和 文档坐标
窗口坐标
指的是浏览器窗口坐标,按照上边和左边计算距离,即便有滚动条这是这么计算的
1. 窗口大小
window.innerWidth 返回数字,不带px
window.innerHeight
ie8
window.docmentElement.clientWidth
window.docmentElement.clientHeight
2. 元素的窗口大小和坐标
元素左上角和右下角距离窗口上边和左边的距离
- ele.getBoundingClientRect() 返回left,right即为坐标,除此之外还有宽高
注:以上方法计算含边框和内边距;数据非实时更新;
document.getElementsByTagName('div')[0].getBoundingClientRect()
//{
bottom: 103
height: 95
left: 8
right: 18
top: 8
width: 10
x: 8 //坐标x
y: 8 //坐标y
}
文档大小和坐标
指算上滚动条的坐标,这个才是经常用的
1. 文档大小
document.documentElement.offsetHeight
document.documentElement.offsetWidth
2. 元素的文档坐标
- 元素窗口坐标+滚动偏移量
x坐标:ele.getBoundingClientRect.left + window.pageXOffSet()
y坐标:ele.getBoundingClientRect.top + window.pageYOffSet()
- 元素相对距离
对于定位或者指定元素,此计算是相对于祖先元素
offset 外
offsetParent 元素的此属性指定相对计算位置
offsetLeft offsetTop 计算坐标,盒子border外边到第一个定位父元素border内边的距离(static除外)
offsetWidth offsetHeight 包含边框的宽高,相当于border-box时的宽高
client 内
clientLeft clientTop 没多大用 (表示一个元素的左border的宽度)
clientWidth clientHeight 宽高,不包含边框,不计算滚动条的宽高
对于span内联元素,client为0(滚动条撑起来的?)
scroll 滚动
scrollLeft scrollTop 可赋值改变滚动条位置
scrollWidth scrollHeight 宽高,含边框和滚动偏移
更多文章可以在个人主页中查看
【前方雾大,关注一下不迷路 = 。=】