Примеры для jQuery .width()


Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>width demo</title>
<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="https://code.jquery.com/jquery-1.10.2.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>&nbsp;</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>

Демонстрация:

Change the width of each div the first time it is clicked (and change its color).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>width demo</title>
<style>
div {
width: 70px;
height: 50px;
float: left;
margin: 5px;
background: red;
cursor: pointer;
}
.mod {
background: blue;
cursor: default;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
<script>
var modWidth = 50;
$( "div" ).one( "click", function() {
$( this ).width( modWidth ).addClass( "mod" );
modWidth -= 8;
});
</script>
</body>
</html>

Демонстрация: