首先看看前端开发涉及到的位置信息有哪些,根据不同的对象,我做了一个下面这样的表格帮助理解
对象 | 属性 | 说明 |
---|---|---|
window | screen.width | 显示屏分辨率(不是物理分辨率) |
window | screen.availHeight | 显示屏分辨率(不包含任务栏) |
window | screenTop | 浏览器窗口左上角相对于屏幕左上角位置 |
window | screenX | 浏览器窗口左上角相对于屏幕左上角位置 |
event | screenX | 鼠标光标相对于屏幕的位置 |
event | clientX | 鼠标光标相对于浏览器的位置 |
event | pageX | 鼠标光标相对于页面的位置 |
dom | clientWidth | dom元素边框内的区域(不包含边框) |
dom | offsetWidth | dom元素边框及边框内的区域 |
dom | scrollWidth | dom元素滚动总区域 |
dom | scrollTop | dom元素已滚动的区域 |
dom | clientTop | dom元素边框区域 |
dom | offsetTop | dom元素margin区域 |
相信你一开始看见这个表格和我一样也是一脸懵逼,没关系,我用看图说话的方式帮助你理解
①window对象的位置信息
screen.width
screen.availWidth
screenLeft
下面是js代码
console.log(window.screen.width);
console.log(window.screen.availWidth);
console.log(window.screenTop);
console.log(window.screenX);
通过图我们可以清晰的看出来他们三者的区别:
1.screenTop和screenLeft是浏览器窗口相对屏幕左上角的位置
2.screen.height和screen.width是显示屏区域(由显示分辨率决定,而不是物理分辨率)
3.screen.availHeight和screen.availWidth是浏览器窗口可覆盖区域(显示屏区域减去任务栏区域的部分)
②event对象的位置信息
下面我们通过鼠标点击事件获取位置
document.body.onclick=function(event){
console.log(event.screenY);
console.log(event.pageY);
console.log(event.clientY);
}
1.screenX和screenY是以屏幕左上角为基准的位置;
2.clientX和clientY是以浏览器客户区左上角为基准的位置,客户区不包括浏览器上方的工具栏;
3.pageX和pageY是以页面左上角为基准的位置,当没有发生滚动时,pageX=clientX;clientY=pageY;发生了滚动以后,二者可能就不相等了,具体看图!
③dom对象有关位置信息
offsetWidth
offsetTop
clientWidth
scrollTop
clientTop
看见这五个属性,是不是头皮发麻,没关系,我们新建一个html来帮助我们更好的理解他们
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="father">
<div class="son">
hello
</div>
</div>
</body>
</html>
我们创建了两个div,一个父div和一个子div
为了更清晰的看出差别,我们为他们做一点样式
<style>
*{
padding: 0;
margin: 0;
}
body{
width: 1920px;
height: 1080px;
background: #eaeaea;
}
.father{
width: 500px;
height: 200px;
margin-left: 50px;
margin-top: 100px;
padding: 50px;
border: 20px solid #6A2C70;
background-color: #B83B5E;
overflow: scroll;
}
.son{
width: 600px;
height: 300px;
padding: 50px;
background: #F9ED69;
border:20px solid #F08A5D;
}
</style>
接下来获取father的dom对象引用, 然后讲他打印出来
<script>
var father=document.getElementsByClassName('father')[0];
document.body.onclick=function(event){
console.log('clientWidth='+father.clientWidth+'px'+'\n'+'clientHeight='+father.clientHeight+'px');
console.log('offsetWidth='+father.offsetWidth+'px'+'\n'+'offsetHeight='+father.offsetHeight+'px');
console.log('scrollTop='+father.scrollTop+'px'+'\n'+'scrollLeft='+father.scrollLeft+'px');
console.log('clientTop='+father.clientTop+'\n'+'clientLeft'+father.clientLeft);
console.log('offsetTop='+father.offsetTop+'\n'+'offsetLeft'+father.offsetLeft);
}
</script>