css client家族
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
1. clientWidth 和 clientHeight
- 返回元素的内部大小,该属性包括内边距 padding,但不包括边框 border、外边距 margin 和滚动条(如果有的话)。
- 返回值是只读属性且始终是整数。
- 一般而言对于块状元素或者行内块元素:
element.clientWidth/Height = 元素自身的宽/高(width/height) + padding
- 对于行内元素
element.clientWidth/Height = 0
例如:
<div class="box" style="width:200px;height:200px"></div>
<span>hello world</span>
<a href="xxx" style="display: inline-block;">行内块标签</a>
<p>hello world</p>
<script>
console.log("box", {
w: $(".box").clientWidth,
h: $(".box").clientHeight
}); // { w: 200, h: 200 }
console.log("span", {
w: $("span").clientWidth,
h: $("span").clientHeight
}); // { w: 0, h: 0 }
console.log("a", {
w: $("a").clientWidth,
h: $("a").clientHeight
}); // { w: 80, h: 21 }
console.log("p", {
w: $("p").clientWidth,
h: $("p").clientHeight
}); // { w: 可视区域的宽, h: 21 }
function $(selector){
return document.querySelector(selector);
}
</script>
注意: 如果元素内容溢出,溢出部分大小不会计算在内。这也是与 scrollWidth和scrollHeight的区别。
var box = $(".box");
box.style.padding = "30px";
box.style.border = "20px solid #00f";
box.innerHTML = "<div style='width: 400px;height: 400px'></div>";
box.style.overflow = "scroll";
console.log("box", {
w: box.clientWidth,
h: box.clientHeight
}); // { w: 243, h: 243 }
2. clientTop 和 clientLeft
- 返回元素上左边框的宽度。
- 返回值为只读属性且始终是整数。
3. 获取页面可视区域宽高
3.1 通过 html 元素获取
document.documentElement.clientWidth/clientHeight
返回只读且始终是整数,不包含浏览器滚动条的宽度(如果有)
3.2 通过 window 获取
window.innerWidth/innerHeight
返回只读且始终是整数,IE < 9 不支持。返回值包含浏览器滚动条的宽度(如果有)
4. 获取元素与可视区域距离
Element.getBoundingClientRect()
方法返回元素的大小及其相对于视口的位置。该方法返回的对象属性包括以下属性:
- top、left、right、bottom 是指元素四周与页面的上左边距。
- width、height 用于获取元素占据页面的尺寸,相当于元素的 offsetWidth 和 offsetHeight 属性。
- x、y 是 left 和 top 属性的简写,存在浏览器兼容问题,目前不推荐使用这两个属性。
<style>
.box{
position: absolute;
top: 50px;
left: 50px;
width: 300px;
height: 200px;
padding: 50px;
border: 20px solid #000;
background-color: #f00;
}
.inner {
position: relative;
width: 200px;
height: 100px;
margin: 20px;
padding: 30px;
background-color: #0f0;
border: 10px solid #9000ff;
}
.insert {
width: 100px;
height: 50px;
margin: 50px;
background-color: #00f;
}
</style>
<body>
<div class="box">
<div class="inner">
<div class="insert"></div>
</div>
</div>
<script>
console.log("box", getDistance($(".box")));
console.log("inner", getDistance($(".inner")));
console.log("insert", getDistance($(".insert")));
function getDistance(ele){
var obj = ele.getBoundingClientRect();
console.log(obj);
return {
top: obj.top,
left: obj.left
}
}
function $(select){
return document.querySelector(select);
}
</script>
</body>
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |