element.offsetTop与element.offsetLeft
offsetTop和offsetLeft是相对于有定位的父元素的偏移,如果没有有定位父元素则是相对与body的距离.
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
.father{
width: 200px;
height: 200px;
position: relative;
top: 1000px;
left: 200px;
background-color: aqua;
}
.son{
width: 100px;
height: 100px;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 50%;
background-color: red;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
div1=document.querySelector('.father')
div2=document.querySelector('.son')
console.log(div1.offsetTop);
console.log(div2.offsetTop);
</script>
</body>
</html>
效果:
但是我有了个疑惑:如果隔了一代有了定位呢?
代码”
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
body{
height: 100vh;
}
.grandfather{
width: 500px;
height: 500px;
position: relative;
background-color: yellow;
float: right;
}
.father{
width: 200px;
height: 200px;
background-color: aqua;
}
.son{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="grandfather">
<div class="father">
<div class="son"></div>
</div>
</div>
<script>
div1=document.querySelector('.father')
div2=document.querySelector('.son')
console.log('father:'+div1.offsetLeft);
console.log('son:'+div2.offsetLeft);
</script>
</body>
</html>
效果:
看看看,都是0,所以明显是相对了grandfather。所以隔代还是有效的
offsetWidth与offsetHeight
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.a{
width: 100px;
height: 100px;
padding: 20px;
margin: 50px;
background-color: violet;
}
.b{
width: 200px;
height: 200px;
border: 15px solid red;
background-color: teal;
}
</style>
</head>
<body>
<div class="a"></div>
<div class="b"></div>
<script>
var diva=document.querySelector('.a')
var divb=document.querySelector('.b')
console.log('diva:'+diva.offsetWidth);
console.log('divb:'+divb.offsetWidth);
</script
</body>
</html>
效果:
注意事项:
border,padding会扩大盒子会被算进offsetWidth和offsetHeight,但是margin不会被算进去。
offsetParent
offsetParent可以隔代,只要找到一个有定位的父元素就行了
区别:
parentNode返回的是最近一级的亲爸爸,不管有没有定位
注意事项: