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

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