<!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>js获取屏幕高度</title>
<script src="../js/jquery-3.4.1.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
height: 3000px;
display: flex;
justify-content: center;
}
.box2 {
margin-top: 700px;
width: 100px;
height: 100px;
padding: 30px;
position: relative;
background-color: aquamarine;
}
.box3 {
width: 70px;
height: 50px;
margin: 25px auto 25px auto;
padding: 10px;
border: 10px solid red;
background-color: coral;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">
<div class="box3"></div>
</div>
</div>
</body>
<script>
function box(e) {
let box2 = document.querySelector('.box2')
let box2OffsetTop = box2.offsetTop
let box2OffsetLeft = box2.offsetLeft
console.log('页面顶部距离', box2OffsetTop); // 页面顶部距离 700
console.log('页面左边距离', box2OffsetLeft); // 页面左边距离 680
// 如果父元素使用position: relative fxied absolute
let box3 = document.querySelector('.box3')
let box3OffsetTop = box3.offsetTop
let box3OffsetLeft = box3.offsetLeft
console.log('子元素距离父元素的top距离', box3OffsetTop); //子元素距离父元素的top距离 55
console.log('子元素距离父元素的left距离', box3OffsetLeft); // 子元素距离父元素的left距离 30
// 子元素距离父元素的距离,注意:这里父元素设置了position: relative fxied absolute;就使用offsetParent就可以定位到父元素上
let box3OffsetTop3 = box3.offsetParent.offsetTop - box3.offsetTop
let box3OffsetLeft3 = box3.offsetParent.offsetLeft - box3.offsetLeft
console.log('父元素设置定位情况下子元素的top位置', box3OffsetTop3); // 父元素设置定位情况下子元素的top位置 645
console.log('父元素设置定位情况下子元素的left位置', box3OffsetLeft3); // 父元素设置定位情况下子元素的left位置 650
// 获取元素宽度和高度 包括 padding 不包括 border
let box3scrollWidth = box3.scrollWidth
let box3scrollHeight = box3.scrollHeight
let box3clientWidth = box3.clientWidth
let box3clientHeight = box3.clientHeight
console.log('元素宽度', box3scrollWidth); // 元素宽度 90
console.log('元素高度', box3scrollHeight); // 元素高度 70
console.log('元素宽度', box3clientWidth); // 元素宽度 90
console.log('元素高度', box3clientHeight); // 元素高度 70
}
box()
</script>
</html>
元素距离页面上的Top和Left
于 2022-06-09 14:36:03 首次发布