<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
}
.father{
width: 200px;
height: 200px;
background: red;
overflow: scroll;
padding: 50px;
border: 50px solid #ccc;
margin: 100px;
position: relative;
}
.son{
width: 400px;
height: 400px;
background: green;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
const father = document.querySelector(".father")
const son = document.querySelector(".son")
father.addEventListener("scroll",function(){
// 位置--滚动条拉动的纵向距离
console.log("滚动条拉动的纵向距离:"+father.scrollTop)
// 位置--滚动条拉动的横向距离
console.log("滚动条拉动的横向距离:"+father.scrollLeft)
})
father.addEventListener("click",function(){
// 尺寸--获取可视区宽度--包含padding,滚动条。不包含border
console.log("父级clientWidth:"+father.clientWidth) //285--父级宽度200+padding50*2-滚动条15=285
// 尺寸--获取可视区高度--包含padding,滚动条。不包含border
console.log("父级clientHeight:"+father.clientHeight)//285--父级高度200+padding50*2-滚动条15=285
// 尺寸--offsetWidth--包含padding,border.不包含滚动条
console.log("父级offsetWidth:"+father.offsetWidth) //400--父级宽度200+padding50*2+border50*2=400
// 尺寸--offsetHeight--包含padding,border.不包含滚动条
console.log("父级offsetHeight:"+father.offsetHeight)//400--父级高度200+padding50*2+border50*2=400
// 尺寸--指定元素内容层的真实宽度--包含隐藏
console.log("父级scrollWidth:"+father.scrollWidth) //500 父级padding50*2+子级宽度400
// 尺寸--指定元素内容层的真实高度--包含隐藏
console.log("父级scrollHeight:"+father.scrollHeight)//500 父级padding50*2+子级高度400
// 位置--offsetTop--当前元素左上角在offsetParent节点内向右偏移的像素数。没有定位,位置数值相对的是body
console.log("父级offsetTop:"+father.offsetTop) //100 margin-top=100
// 位置--offsetLeft--当前元素左上角在offsetParent节点内向下偏移的像素数。没有定位,位置数值相对的是body
console.log("父级offsetLeft:"+father.offsetLeft)//100 margin-left=100
console.log("子级clientWidth:"+son.clientWidth) //400--不会计算被隐藏的部分
console.log("子级clientHeight:"+son.clientHeight)//400--不会计算被隐藏的部分
console.log("子级offsetWidth:"+son.offsetWidth) //400
console.log("子级offsetHeight:"+son.offsetHeight)//400
console.log("子级scrollWidth:"+son.scrollWidth) //400
console.log("子级scrollHeight:"+son.scrollHeight)//400
// 位置--offsetTop--当前元素左上角在offsetParent节点内向右偏移的像素数。父级元素定位后,位置数值相对的是父级元素
console.log("子级offsetTop:"+son.offsetTop) //50 父级position: relative;后,相对父级定位,父级padding50
// 位置--offsetLeft--当前元素左上角在offsetParent节点内向下偏移的像素数。父级元素定位后,位置数值相对的是父级元素
console.log("子级offsetLeft:"+son.offsetLeft)//50 父级position: relative;后,相对父级定位,父级padding50
})
</script>
</body>
</html>
JavaScript--scrollTop,clientHeight,offsetHeight,scrollHeight,offsetTop的案例
于 2025-02-27 10:28:00 首次发布