概述 .outerWidth( [includeMargin ] )
返回值:Number
描述: 获取匹配元素集合中第一个元素的当前计算外部宽度(包括padding,border和可选的margin)
false
)
Boolean
返回元素的宽度,包括左右 padding值,border值和可选择性的margin。单位为像素。如果在一组空的元素集合上调用,返回undefined
(在jQuery 3.0之前返回null
)。
这个方法不适用于window
和 document
对象,可以使用.width()
代替。虽然.outerWidth()
可以用于表格(table)元素,它可能会在使用border-collapse: collapse
CSS属性的表格(table)元素上给出意外的结果。
.outerWidth()
,在某些情况下可能是小数。你的代码不应该假定它是一个整数。
另外,当页面被用户放大或缩小时,尺寸可能不正确的;浏览器没有公开的API来检测这种情况。
.outerWidth()
得到的值不能保证准确。要得到准确的值,你应该确保该元素在使用.outerWidth()
前可见。jQuery将尝试临时显示,然后再隐藏元素来测量元素尺寸,但这是不可靠的,(即使得到准确的值)也会显著影响页面的性能。这总临时显示然后再隐藏的测量功能,可能在jQuery未来的版本中删除。
Example
获取一个段落的outerWidth。
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>outerWidth demo</title>
- <style>
- p {
- margin: 10px;
- padding: 5px;
- border: 2px solid #666;
- }
- </style>
- <script src="//code.jquery.com/jquery-1.10.2.js"></script>
- </head>
- <body>
-
- <p>Hello</p><p></p>
-
- <script>
- var p = $( "p:first" );
- $( "p:last" ).text(
- "outerWidth:" + p.outerWidth() +
- " , outerWidth( true ):" + p.outerWidth( true ) );
- </script>
-
- </body>
- </html>
概述 .outerWidth( value )
返回值:jQuery
描述: 为匹配集合中的每个元素设置CSS外部宽度。
String
, Number
this
指向集合中的当前元素。
当调用.outerWidth("value")
方法的时候,这个“value”参数可以是一个字符串(数字加单位)或者是一个数字。如果这个“value”参数只提供一个数字,jQuery会自动加上像素单位(px)。如果只提供一个字符串,应该是任何有效的可以为宽度赋值的CSS尺寸(就像100px
, 50%
, 或者 auto
)。
Example
每个div首次被点击时改变它的外部宽度(和改变其颜色)。
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>outerWidth demo</title>
- <style>
- div {
- width: 60px;
- padding: 10px;
- height: 50px;
- float: left;
- margin: 5px;
- background: red;
- cursor: pointer;
- }
- .mod {
- background: blue;
- cursor: default;
- }
- </style>
- <script src="//code.jquery.com/jquery-1.10.2.js"></script>
- </head>
- <body>
-
- <div>d</div>
- <div>d</div>
- <div>d</div>
- <div>d</div>
- <div>d</div>
-
- <script>
- var modWidth = 60;
- $( "div" ).one( "click", function() {
- $( this ).outerWidth( modWidth ).addClass( "mod" );
- modWidth -= 8;
- });
- </script>
-
- </body>
- </html>