.width()
.width()
描述:获得匹配的元素集合中的第一个元素的当前经计算的宽度。
该方法不接受任何参数
.css( "width" )和.width()的区别在后,后者返回一个无单位的像素值(比如说,400),而前者返回一个带完整单位的值(比如说,400px)。如果元素的高度需要用在数学计算中,推荐使用该.width()方法。

该方法也可以用来找到windows和document的宽度。
// 返回浏览器视口的宽度 $( window ).width(); // 返回HTML document的宽度 $( document ).width();
注意.width()将总是返回内容的宽度,无论CSS的box-sizing属性如何设置。自从jQuery 1.8,这可能需要检索CSS的宽度加上box-sizing属性,然后如果元素具有box-sizing: border-box,还要减去每个元素上任何潜在的边框和内衬。要想避免这种处罚,请使用.css( "width" )而不是使用.width()。
注意:虽然<style>和<script>标签被设置了绝对定位并给定了display:block时,它们将对.width或.height()报告其值,但是强烈不建议在这些标签上调用那些方法。除了是一个糟糕的实践,结果也被证明是不可靠的。
其它说明
- 维度相关的API返回的数字,包括
.width(),在一些情况中可能是分数。代码不应该假定它是一个整数。当用户缩放网页的时候,维度可能不正确;浏览器没有提供侦测这种情况的API。 - 当元素或者它的父元素是隐藏元素的时候,
.width所报告的值不能保证精确。要想获得精确的值,在使用.width()之前请先检查元素的可见性。jQuery会试图临时地显示,然后再次隐藏元素,以测量它的维度,但是这是不可靠的,而且(甚至当精确测量时)会显著地影响了网页的性能。这种显示再重新隐藏的测主功能可能在jQuery的未来版本中被删除。
示例
显示各种各样的宽度。注意值来自iframe,所以可能小于你的期待。黄色的高亮显示了iframe的主体。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>width demo</title>
<style>
body {
background: yellow;
}
button {
font-size: 12px;
margin: 2px;
}
p {
width: 150px;
border: 1px red solid;
}
div {
color: red;
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="getp">Get Paragraph Width</button>
<button id="getd">Get Document Width</button>
<button id="getw">Get Window Width</button>
<div> </div>
<p>
Sample paragraph to test width
</p>
<script>
function showWidth( ele, w ) {
$( "div" ).text( "The width for the " + ele + " is " + w + "px." );
}
$( "#getp" ).click(function() {
showWidth( "paragraph", $( "p" ).width() );
});
$( "#getd" ).click(function() {
showWidth( "document", $( document ).width() );
});
$("#getw").click(function() {
showWidth( "window", $( window ).width() );
});
</script>
</body>
</html>
演示结果
.width()
描述:针对每个匹配的元素设置宽度。
在调用.width(value)时,这个值可以是一个字符串(数字以及单位),或者是一个数字。如果只为该值提供了一个数字,jQuery假定单位是px。然而如果提供了一个字符串,必须为宽度提供一个有效的CSS测量(比如说100px、50%或者auto)。注意,在现代浏览器中,CSS宽度属性不包括padding、border或者margin,除非用了CSS属性box-sizing。
如果没有明确指定单位(比如说“em”或者“%”),则单位就是“px”。
注意,.width(value)设置了盒的内容宽度,无论CSS属性box-sizing设置了什么值。
示例
每个div第一次被点击时,改变它的宽度(并改变颜色)。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>width demo</title>
<style>
div {
width: 70px;
height: 50px;
float: left;
margin: 5px;
background: red;
cursor: pointer;
}
.mod {
background: blue;
cursor: default;
}
</style>
<script src="https://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 = 50;
$( "div" ).one( "click", function() {
$( this ).width( modWidth ).addClass( "mod" );
modWidth -= 8;
});
</script>
</body>
</html>
演示结果