1、offsetLeft/Top
offsetLeft/offsetTop是相对于offsetParent左上角的x/y坐标。
offsetParent是最接近的祖先元素,成为最接近的祖先元素为下列条件之一:
1.css定位(position为absolute,relative或fixed)
2.元素为td th table
3.body元素
<style>
.main{
position: absolute;
left: 150px;
top: 80px;
width: 100px;
height: 100px;
border: 10px solid red;
padding: 10px;
overflow: auto;
}
</style>
<body>
<div class="main">随便写点内容哈哈哈哈哈哈</div>
</body>
<script>
var main = document.querySelector('.main')
console.log('main.offsetParent====',main.offsetParent)
console.log('main.offsetLeft====',main.offsetLeft) // 150
console.log('main.offsetTop====',main.offsetTop) // 80
</script>
2、offsetWidth/Height
offsetWidth/Height提供了元素的“外部”width/height,它的大小包括边框。
console.log('main.offsetWidth====',main.offsetWidth) // 140 = 100 + 左右padding10x2 + 左右border10x2
console.log('main.offsetHeight====',main.offsetHeight) // 140 = 100 + 上下padding10x2 + 上下border10x2
3、clientLeft/Top
clientLeft/Top一般指的是左边框宽度/上边框宽度。
console.log('main.clientLeft====',main.clientLeft) // 10
console.log('main.clientTop====',main.clientTop) // 10
4、clientWidth/Height
clientWidth/Height提供了元素边框内区域的大小,它包括’content width’和’padding’,但不包括border和滚动条。
console.log('main.clientWidth====',main.clientWidth) // 120 = 100 + 左右padding10
console.log('main.clientHeight====',main.clientHeight) // 120 = 100 + 上下padding10
5、scrollWidth/Height
scrollWidth/Height就像clientWidth/Height,但它们还包括滚动出的部分。
main div中加一些文字,出现滚动条。
<body>
<div class="main">火车站西广场~银基~陇海路紫金山路~未来路~
中州大道郑汴路~黄河南路~陇海路八大街~高铁站~莆田高速口
~航海路十三大街~经南三路~南三环十七大街~双汇~航海路前程大道
~宇通新能源~22大街~浔江东路~八岗~大营 ~尉氏县城。</div>
</body>
console.log('main.scrollWidth====',main.scrollWidth) // 103
console.log('main.scrollHeight====',main.scrollHeight) // 503
6、scrollLeft/Top
scrollLeft/scrollTop是元素的隐藏、滚动部分的width/height。
最后附一张图来概括这几个属性: