返回值:Integerwidth()

取得匹配集合中第一个元素经过计算后的宽度。

.css(width).width() 的区别在于,后者返回的是不带单位的像素值(例如, 400)。然而,前者返回的是带单位的值(例如,400px)。建议在需要对元素的宽度进行数学计算的场合使用 .width() 方法。

该方法同样可以取得 window 和 document 的宽度。

$(window).width();   // returns width of browser viewport
$(document).width(); // returns width of HTML document

注意,.width() 总是返回内容的宽度,而不考虑 CSS 属性 box-sizing 的值。

示例:

显示不同元素的宽度。注意,由于例子中的宽度值是来自 iframe 的,因此可能比实际值小。以黄色高亮形式显示的就是 iframe 的内主体。

<!DOCTYPE html>
<html>
<head>
<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="jquery.min.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>&nbsp;</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>

演示:

返回值:jQuerywidth(value)

为每个匹配的元素设置 CSS 宽度。

当调用 .width(value) 时,value 参数既可以是字符串(数字和单位),也可以是数字。如果是数字的话,jQuery 会假定其单位是像素。如果是字符串的话,则必须使用有效的 CSS 宽度单位(例如 100px, 50%, 或 auto)。注意,在主流的浏览器中,CSS 宽度属性不包含 padding, border, 或 margin。

如果不显式的指定单位(像 'em' 或 '%'),那么会使用 "px" 连接数值。

注意,使用 .width(value) 设置盒子的宽度与 CSS 属性 box-sizing 是一致的。如果将这个属性换成 border-box,则会导致该函数将改变盒子的 outerWidth 而不是内容的宽度。

示例:

第一次点击 div 时,改变它的宽度和颜色。

<!DOCTYPE html>
<html>
<head>
<style>
div { width: 70px; height: 50px; float:left; margin: 5px;
        background: red; cursor: pointer; }
.mod { background: blue; cursor: default; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>


  <div>d</div>
  <div>d</div>
  <div>d</div>
  <div>d</div>
  <div>d</div>


<script>


(function() {
  var modWidth = 50;
  $("div").one('click', function () {
    $(this).width(modWidth).addClass("mod");
  modWidth -= 8;
  });
})();


</script>
</body>
</html>

演示: