对Javascript中client系列(clientTop、clientLeft、clientWidth和clientHeight)属性的相关解释和相关DOM操作

  1. clientTop:clientTop可以返回div的上边框的大小,其值为一个整数,没有单位。但是和borderTopWidth存在一定的区别。
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>与client有关</title>
	<style type="text/css">
		#container{
			width: 200px;
			height: 100px;
			border: 10.5px solid blue;
			background-color: yellow;
		}
	</style>
</head>
<body>
	<div id="container" style="color:red">
		容器
	</div>
</body>
<script>
	const container = document.getElementById('container');
	console.log(container.clientTop);
	console.log(getComputedStyle(container,null).borderTopWidth);
	console.log(container.style.color);
	console.log(container.style.borderTopWidth);
</script>
</html>

运行结果:
在这里插入图片描述
可见,clientTop返回的是整数并且没有单位。而borderTopWidth返回的是container的上边框的厚度,是精确的。两者之间的关系是:

container.clientTop = Math.round(parseFloat(getComputedStyle(container,null).borderTopWidth));

还可以看出,element.style.***只能得到行内style里面的属性。但是getComputedStyle可以得到在"text/css"里面的css属性,但是此方法只能获取属性,不能设置。getComputedStyle:该属性是兼容火狐谷歌,不兼容IE,currentStyle:该属性只兼容IE,不兼容火狐和谷歌。
2.clientLeft:clientLeft和clientTop原理相同,返回元素左边框的宽度。其值为一个整数,没有单位
3.clientHeight:clientHeight返回元素客户区的高度。clientHeight = height + padding-top + padding-buttom;其值为一个整数,没有单位
3.clientWidth:clientWidth返回元素客户区的宽度。clientWidth= width + padding-left + padding-right;其值为一个整数,没有单位

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>与client有关</title>
	<style type="text/css">
		#container{
			width: 200px;
			height: 40px;
			border-top: 25.5px solid red;
			border-left: 20.5px solid pink;
			border-right: 20px solid green;
			border-bottom: 18px solid blue;
			padding: 30px;
		}
		#inner{
			border: 1px solid black;
			width: 180px;
			height: 50px;
			text-align: center;
			line-height: 50px;
		}
	</style>
</head>
<body>
	<div id="container" style="color:red">
		<div id='inner'>content</div>
	</div>
</body>
<script>
	const container = document.getElementById('container');
	console.log(container.clientHeight);
	console.log(container.clientWidth);
	console.log(container.clientTop);
	console.log(container.clientLeft);
	
</script>
</html>

结果:
在这里插入图片描述
上图表示clientTop、clientLeft、clientHeight、clientWidth具体内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值