前段日子,公司需要一个音频播放器组件,就自己实现了一个,其中进度条的点击,拖拽,会涉及到标题中的几个距离,闲下来的时候做实验总结了,以后就更加通透了。(内心OS:勤快一点总是好的)
先介绍结论,后面介绍实验过程,后面可以根据实验结果加深理解:
clientWidth和clientHeight
clientWidth是只包括content和padding的元素的宽度,
clientHeight是只包括content和padding的元素的高度
offsetWidth和offsetHeight
offsetWidth是包括content,padding,border的元素的宽度,
offsetHeight是包括content,padding,border的元素的高度
clientTop和clientLeft
clientTop:上边框的宽度,
clientLeft:左边框的宽度
offsetTop和offsetLeft
相对父元素的上偏移距离和左偏移距离。
如果父元素没有定位的话就相对于body
scrollHeight和scrollWidth
scrollHeight: 获取对象的滚动高度。
scrollWidth:获取对象的滚动宽度
scrollTop和scrollLeft
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
Tips
- 网页可见区域宽: document.body.clientWidth;
- 网页可见区域高: document.body.clientHeight;
- 网页可见区域宽: document.body.offsetWidth (包括边线的宽);
- 网页可见区域高: document.body.offsetHeight (包括边线的宽);
- 网页正文全文宽: document.body.scrollWidth;
- 网页正文全文高: document.body.scrollHeight;
- 网页被卷去的高: document.body.scrollTop;
- 网页被卷去的左: document.body.scrollLeft;
- 屏幕分辨率的高: window.screen.height;
- 屏幕分辨率的宽: window.screen.width;
我这里son和box是采用相对定位和决定定位的。而father和son没有采用,目的是为了重点比较offsetTop,offsetLeft,你们也可以看出不一样。
获得Dom元素并打印,结果如下:
window.onload = function(){
let fatherDom = document.querySelector('.father')
console.log(fatherDom.clientWidth, fatherDom.clientHeight) //120 120
console.log(fatherDom.offsetWidth, fatherDom.offsetHeight) // 130 130
console.log(fatherDom.clientTop, fatherDom.clientLeft) // 5 5
console.log(fatherDom.offsetTop, fatherDom.offsetLeft) //105 100
console.log('======')
let sonDom = document.querySelector('.son')
console.log(sonDom.clientWidth, sonDom.clientHeight) //70 70
console.log(sonDom.offsetWidth, sonDom.offsetWidth) // 80 80
console.log(sonDom.clientTop, sonDom.clientLeft) // 5 5
console.log(sonDom.offsetTop, sonDom.offsetLeft) //145 135
console.log('======')
let boxDom = document.querySelector('.box')
console.log(boxDom.clientWidth, boxDom.clientHeight) //20 20
console.log(boxDom.offsetWidth, boxDom.offsetWidth) // 20 20
console.log(boxDom.clientTop, boxDom.clientLeft) // 0 0
console.log(boxDom.offsetTop, boxDom.offsetLeft) //25 25
somDom.addEventListener('click', handleClick)
}
鼠标点击事件获得的属性
如果我们点击某个元素,会在e中得到许多属性,下面讨论clientX,offsetX,pageX,screenX的区别。
这里先放上实验图。
clientX和clientY
点击位置相对于浏览器窗口可视区域的X,Y坐标,可视区域不包括工具栏和滚动条。
如上图所示点击中间点,
clientX为175(来源:100+5+10+20+5+10+25)
clientY为185(来源:105+5+10+25+5+10+25)
offsetX和offsetY
点击事件相对于该元素的左偏移距离,和上偏移距离。以元素左上角,不包括border为零点。
下图红点为点击位置,括号里的值分别为offsetX和offsetY
pageX和pageY
点击的点相对于页面的偏移量。(注意:包括页面被卷进去的部分)。如果页面没有被卷进去的部分,则跟clientX,clientY相同。
screenX和screenY
相对于用户屏幕左上角的偏移量。包括浏览器工具栏什么的。
如果有不对的地方请指正。