jQuery width()
jQuery width()方法用于返回或设置匹配元素的宽度。
要返回宽度: 使用此方法返回宽度时,它将返回第一个匹配元素的宽度。
设置宽度:使用此方法设置宽度时,它将为每个匹配的元素设置宽度。
此方法是jQuery维度之一。
jQuery维度列表:
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
语法:
要返回宽度:
设置宽度:
使用功能设置宽度:
$(selector).width(function(index,currentwidth))
jQuery width()方法的参数
参数 |
说明 |
value |
这是必填参数。用于设置宽度。它以px,em,pt等指定宽度。jQuery width()方法的默认值为px。 |
function(index,currentwidth) |
这是一个可选参数。它指定了一个提供选定元素新宽度的函数。 index:提供了元素在集合中的索引位置。 currentwidth::它提供所选元素的当前宽度。 |
jQuery width()方法的示例
让我们以一个示例来演示jQuery width()方法的效果。
返回宽度:
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Width of div: " + $("div").width());
});
});
</script>
</head>
<body>
<div style="height:100px;width:200px;padding:10px;margin:3px;border:1px solid blue;background-color:lightpink;"></div><br>
<button>Execute the jQuery width() method to return width</button>
</body>
</html>
输出:
jQuery width()示例2
要设置宽度:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>width demo</title>
<style>
div {
width: 100px;
height: 80px;
float: left;
margin: 5px;
background:orange;
cursor: pointer;
}
.mod {
background: green;
cursor: default;
}
</style>
<script src="/jquery-1.10.2.js"></script>
</head>
<body>
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
<script>
var modWidth = 70;
$("div").one( "click", function() {
$( this ).width( modWidth ).addClass( "mod");
modWidth -= 10;
});
</script>
</body>
</html>
输出: