返回值:Integerwidth()
取得匹配集合中第一个元素经过计算后的宽度。
-
1.0 新增width()
.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> </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>