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


Access the offset of the second paragraph:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
var p = $( "p:last" );
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
</script>
</body>
</html>

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

Click to see the offset.

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left: 10px;
color: blue;
width: 200px;
cursor: pointer;
}
span {
color: red;
cursor: pointer;
}
div.abs {
width: 50px;
height: 50px;
position: absolute;
left: 220px;
top: 35px;
background-color: green;
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="result">Click an element.</div>
<p>
This is the best way to <span>find</span> an offset.
</p>
<div class="abs">
</div>
<script>
$( "*", document.body ).click(function( event ) {
var offset = $( this ).offset();
event.stopPropagation();
$( "#result" ).text( this.tagName +
" coords ( " + offset.left + ", " + offset.top + " )" );
});
</script>
</body>
</html>

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

Set the offset of the second paragraph:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>offset demo</title>
<style>
p {
margin-left: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p><p>2nd Paragraph</p>
<script>
$( "p:last" ).offset({ top: 10, left: 30 });
</script>
</body>
</html>

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