返回值:Integerwidth()
Get the current computed width for the first element in the set of matched elements.
-
1.0 新增width()
The difference between .css(width)
and .width()
is that the latter returns a unit-less pixel value (for example, 400
) while the former returns a value with units intact (for example, 400px
). The .width()
method is recommended when an element's width needs to be used in a mathematical calculation.
This method is also able to find the width of the window and document.
$(window).width(); // returns width of browser viewport $(document).width(); // returns width of HTML document
Note that .width()
will always return the content width, regardless of the value of the CSS box-sizing
property.
示例:
Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the 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="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>