浅谈JavaScript元素的尺寸和位置相关属性

1、offsetWidthoffsetHeight

描述元素外尺寸,元素内容+内边距+边框,不包括外边距和滚动条。

2、clientWidth和clientHeight

描述元素内尺寸,元素内容+内边距,不包括边框(IE下实际包括)、外边距、滚动条。

3、scrollWidth和scrollHeight

元素内容+内边距+溢出尺寸,当内容没有溢出时,scrollWidth和scrollHeight一般分别与clientWidth和clientHeight相等,但实际上不同浏览器有不同处理,它们未必相等。

4、offsetLeft 和offsetTop

描述元素的左上角(边框的外边缘)与已定位的父容器(offsetParent对象——元素最近的定位为relative或absolute的祖先元素,若没有则返回null)左上角的距离。

5、clientLeft 和clientTop

描述内边距的外边缘和边框的外边缘之间的水平和垂直距离,也即左、上边框宽度。

6、scrollLeft和scrollTop

描述元素滚动条的位置,可写。


<!doctype html>  
<html>  
    <head>  
        <style type="text/css">  
			#out{
				width:200px;
				height:200px;
				background:red;
				position:absolute;
				left:200px;
				top:1000px;
				padding:5px;
				border:5px solid grey;
			}
			#in{
				width:50px;
				height:50px;
				position:absolute;
				left:50px;
				top:25px;
				background:blue;
				padding:5px;
				border:5px solid grey;
			}
        </style>  
    </head>  
    <body>   
		<div id="out">
			<div id="in"></div>
		</div>
		<script>
			var in_div = document.getElementById("in");
			console.log(in_div.offsetHeight); // 输出:70
			console.log(in_div.clientHeight); // 输出:60
			console.log(in_div.scrollHeight); // 输出:60
			console.log(in_div.offsetTop); // 输出:25
			console.log(in_div.clientTop); // 输出:5
			var out_div = document.getElementById("out");
			console.log(out_div.offsetHeight); // 输出:220
			console.log(out_div.clientHeight); // 输出:210
			console.log(out_div.scrollHeight); // 输出:210
			console.log(out_div.offsetTop); // 输出:1000
			console.log(out_div.clientTop); // 输出:5
			document.body.onscroll = function() { // 页面滚动时触发节流函数
				throttle(scroll, window);
			}
			function scroll() {
				console.log(document.body.scrollLeft);
				console.log(document.body.scrollTop);
			}
			function throttle(method, context) { // 函数节流
				clearTimeout(method.tId);
				method.tId = setTimeout(function() {
					method.call(context);
				}, 100);
			}
		</script>
    </body>  
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值