一、快捷尺寸

一、快捷尺寸

1.1 clientWidth和clientHeight

1
2
3
4
5
6
7
8
9
#box {
float: left;
padding: 10px;
background-color: red;
border: 10px solid #000;
}
img {
display: block;
}

执行代码:

1
2
3
4
5
6
7
8
9
10
// 获取元素
var box = document.getElementById("box");

console.log(box.clientWidth);

// 图片不能直接使用 执行时,图片传输出去,但结果未获取 需要当所有资源加载完之后再执行
window.onload = function(){
console.log(box.clientWidth);
console.log(box.clientHeight);
}

输出结果:

UMKV39.png

总结:

1
2
clientWidth = content + padding
clientHeight = content + padding

1.2 offsetWidth和offsetHeight

执行代码:

1
2
3
4
5
var box = document.getElementById("box");
window.onload = function(){
console.log(box.offsetWidth);
console.log(box.offsetHeight);
}

输出结果:

UMKnnx.png

总结:

1
2
clientWidth = content + padding + border
clientHeight = content + padding + border

1.3 clientLeft和clientTop

  • clientLeft:左边框的宽度

  • clientTop:上边框的宽度

1
2
3
4
5
6
7
#box {
float: left;
padding: 10px;
background-color: red;
border: 10px solid #000;
border-left-width: 20px;
}

执行代码:

1
2
3
4
// 不涉及内容,不需要在全部加载完毕之后再执行
var box = document.getElementById("box");
console.log("clientLeft的值是:" + box.clientLeft);
console.log("clientTop的值是:" + box.clientTop);

结果:

UMKKHK.png

1.4 jquery中的快捷尺寸

1
2
3
4
5
6
7
8
#box {
float: left;
padding: 10px;
background-color: red;
border: 10px solid #000;
border-left-width: 20px;
margin: 20px;
}

执行代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script src="js/jquery-3.4.1.min.js"></script>
<script>
// 获取元素
var $box = $("#box");

// content width()
console.log("content宽是:" + $box.width());
console.log("content高是:" + $box.height());

// content + padding innerWidth()
console.log("innerWidth:" + $box.innerWidth());
console.log("innerHeight:" + $box.innerHeight());

// content + padding +border outerWidth()
console.log("outerWidth:" + $box.outerWidth());
console.log("outerHeight:" + $box.outerHeight());

// content + padding + border + margin outerWidth(true)
console.log("outerWidth(true):" + $box.outerWidth(true));
console.log("outerHeight(true):" + $box.outerHeight(true));
</script>

结果:

UMK14e.png

点击查看

本文标题:一、快捷尺寸

文章作者:Mango

发布时间:2020年07月13日 - 22:34:54

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/b17b8b19.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------