.width()
.width() 返回: Integer
描述: 為匹配的元素集合中獲取第一個元素的當前計算寬度值。
version added: 1.0.width()
.css(width) 和 .width()之間的區(qū)別是后者返回一個沒有單位的數(shù)值(例如,400),前者是返回帶有完整單位的字符串(例如,400px)。當一個元素的寬度需要數(shù)學計算的時候推薦使用.width() 方法 。

這個方法同樣能計算出window和document的寬度。
$(window).width(); // returns width of browser viewport $(document).width(); // returns width of HTML document
注意.width()總是返回內(nèi)容寬度,不管CSS box-sizing屬性值。
Example:
顯示各個寬度。注意這個來自值iframe的值可能小于你的預期。黃色高亮顯示iframe body。
<!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="http://code.jquery.com/jquery-latest.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> </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>
Demo:
.width( value ) 返回 jQuery
描述: 給每個匹配的元素設置CSS寬度。
-
version added: 1.0.width( value )
value一個正整數(shù)代表的像素數(shù),或是整數(shù)和一個可選的附加單位(默認是:“px”)(作為一個字符串)。
-
version added: 1.4.1.width( function(index, width) )
function(index, width)返回用于設置寬度的一個函數(shù)。接收元素的索引位置和元素舊的高度值作為參數(shù)。
當調(diào)用.width(value)方法的時候,這個“value”參數(shù)可以是一個字符串(數(shù)字加單位)或者是一個數(shù)字。如果這個“value”參數(shù)只提供一個數(shù)字,jQuery會自動加上單位px。如果只提供一個字符串,任何有效的CSS尺寸都可以為寬度賦值(就像100px, 50%, 或者 auto)。注意在現(xiàn)代瀏覽器中,CSS寬度屬性不包含padding, border, 或者 margin。除非box-sizing CSS屬性被使用。
如果沒有給定明確的單位(像'em' 或者 '%'),那么默認情況下"px"會被直接添加上去(也理解為"px"是默認單位)。
注意.width('value')設置的容器寬度是根據(jù)CSS box-sizing屬性來定的, 將這個屬性值改成border-box將造成這個函數(shù)改變成獲取這個容器的outerWidth替換原來的內(nèi)容寬度。
Example:
點擊每個div時設置該div寬度為30px,并改變顏色。
<!DOCTYPE html>
<html>
<head>
<style>
div { width:70px; height:50px; float:left; margin:5px;
background:red; cursor:pointer; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div></div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
<script>
$("div").one('click', function () {
$(this).width(30)
.css({cursor:"auto", "background-color":"blue"});
});
</script>
</body>
</html>