注:本联系主要讲解的属性为:clientHeight、clientWidth、offsetParent、offsetWidth、offsetHeight、offsetLeft、offsetRight、scrollWidth、scrollHeight、scrollTop、scrollLeft
效果图:
源码及解析:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>其他样式相关属性</title>
<style>
#box1{
float: left;
width: 100px;
height: 100px;
background-color: wheat;
padding: 20px;
border: 20px solid tomato;
margin: 20px;
}
#box5{
margin: 20px;
height: 300px;
width: 200px;
background-color: wheat;
float: left;
overflow: auto;
}
#box6{
height: 400px;
width: 300px;
background-color: aqua;
}
</style>
<script>
window.onload = function(){
var box2 = document.getElementById("box2");
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function(){
/*
clientWith
clientHeight
这两个属性可以获取元素的可见宽度和高度
这些属性都是不带px的,返回都是一个数字,可以直接进行运算
会获取元素宽度和高度,包括内容区和内边距,不包括边框
这些属性都是制度的,不能修改
offsetWidth
offsetHeight
获取元素的整个宽度和高度,包括内容区、内边距和边框
不包括外边距
offsetParent
可以用来获取当前元素的定位父元素
会获取到离当前元素最近的开启了定位的祖先元素
如果所有的祖先元素都没有开启定位,则返回body
offsetLeft
当前元素相对于其定位父元素的水平偏移量
offsetRight
当前元素相对于其父元素的垂直偏移量
scrollWidth
scrollHeight
可以获取元素整个滚动区的宽度和高度
scrollLeft
可以获取水平滚动条滚动的距离
scrollRight
可以获取垂直滚动条滚动的距离
*/
console.log(box1.clientWidth);
console.log(box1.clientHeight);
console.log(box1.offsetHeight);
console.log(box1.offsetWidth);
console.log(box2.offsetParent.id);
console.log(box2.offsetLeft);
console.log(box2.offsetHeight);
console.log(box5.scrollLeft);
console.log(box5.scrollTop);
console.log(box5.clientHeight);
console.log(box5.clientWidth);
//当满足 scrollHeight - scrollTop == clientHeight
//说明垂直滚动条滚动到底了
console.log(box5.scrollHeight-box5.scrollTop);
//当满足 scrollWidth - scrollTop == clientWidth
//说明水平滚动条滚动到末尾了
console.log(box5.scrollWidth - box5.scrollLeft);
}
}
</script>
</head>
<body id="body">
<button id="btn01">CLICK</button>
<br>
<br>
<div id="box1"></div>
<div id="box3" style="float: left;
position: relative; width: 200px; height: 200px; background-color: brown;">
<div id="box4" style="margin: 50px auto; width:100px; height: 100px; background-color: wheat;">
<div id="box2" style="width: 50px; height: 50px; position: relative;
background-color: blue; margin: auto;"></div>
</div>
</div>
<div id="box5">
<div id="box6"></div>
</div>
</body>
</html>
希望本案例对你有所帮助,加油!