在 jQuery 中,对于个别样式的操作,共有以下 3 种。
本节教程先来介绍获取和设置元素的宽高,后两个之后介绍。
在 jQuery 中,如果想要获取和设置一个元素的宽度和高度,我们可以使用 css() 方法来实现。不过,为了更加灵活地操作元素的宽度和高度,jQuery 另外为我们提供了更多、更强大的方法。
在 jQuery 中,如果我们想要“获取”和“设置”元素的宽度和高度,共有 3 组方法,
如表 1 和表 2 所示。
方法 | 范围 |
---|---|
width() | width |
innerWidth() | width + padding |
outerWidth() | width + padding + border |
方法 | 范围 |
---|---|
height() | height |
innerHeight() | height + padding |
outerHeight() | height + padding + border |
实际上,上面这3组方法是根据 CSS 盒子模型来划分的,如图 1 所示。
对于这 3 组方法,一般情况下我们只会用到 width() 和 height() 这一组方法,其他两组方法了解一下即可。
语法:
width() 方法用于获取和设置元素的宽度,height() 方法用于获取和设置元素的高度。
jQuery 的很多方法都有这样一个特点:没有参数的方法表示“获取”,带有参数的方法表示“设置”。
举例:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <style type="text/css">
- #box1,#box2
- {
- display:inline-block;
- width:100px;
- height:60px;
- border:1px solid gray;
- }
- </style>
- <script src="js/jquery-1.12.4.min.js"></script>
- <script>
- $(function () {
- $("#btn_get").click(function(){
- var width = $("#box1").width();
- alert(width);
- });
- $("#btn_set").click(function(){
- $("#box2").width(50);
- });
- })
- </script>
- </head>
- <body>
- <div id="box1"></div>
- <div id="box2"></div><br />
- 获取第1个div的宽度:<input id="btn_get" type="button" value="获取"/><br/>
- 设置第2个div的宽度:<input id="btn_set" type="button" value="设置">
- </body>
- </html>
预览效果如图 2 所示。
这里要注意一下,width(n) 方法用于设置宽度时是不需要加单位的,像 width(50px) 这种写法是错误的,正确的写法应该是 width(50)。