本文概述
jQuery width()方法用于返回或设置匹配元素的宽度。
返回宽度:使用此方法返回宽度时, 它将返回第一个匹配元素的宽度。
设置宽度:使用此方法设置宽度时, 它将为每个匹配的元素设置宽度。
此方法是jQuery维度之一。
jQuery尺寸列表:
- 宽度()
- 高度()
- innerWidth()
- innerHeight()
- outsideWidth()
- outsideHeight()
句法:
要返回宽度:
$(selector).width()
设置宽度:
$(selector).width(value)
要使用功能设置宽度:
$(selector).width(function(index, currentwidth))
jQuery width()方法的参数
参数 | 描述 |
---|---|
Value | 它是必填参数。用于设置宽度。它以px, em, pt等指定宽度。jQuery width()方法的默认值为px。 |
Function(index, currentwidth) | 它是一个可选参数。它指定一个函数, 该函数提供选定元素的新宽度。 Index:IIt提供元素在集合中的索引位置。 currentwidth:提供所选元素的当前宽度。 |
jQuery width()方法的示例
让我们以一个示例来演示jQuery width()方法的效果。
要返回宽度:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/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="https://code.jquery.com/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>
立即测试
评论前必须登录!
注册