jQuery 获取元素相对浏览器的位置可以使用 .offset() 方法。这个方法返回一个包含 top 和 left 属性的对象,表示元素相对于文档的偏移量。
.offset() 方法:jQuery 提供的一个方法,用于获取元素相对于文档的偏移量。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Offset Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myElement" style="position: absolute; top: 100px; left: 200px;">
Click me to get my position!
</div>
<script>
$(document).ready(function() {
$('#myElement').click(function() {
var offset = $(this).offset();
alert('Top: ' + offset.top + ', Left: ' + offset.left);
});
});
</script>
</body>
</html>.offset() 方法语法简洁,易于理解和使用。.offset() 返回的是元素相对于文档的绝对位置。.offset() 方法返回的值不准确position 属性设置为 static,或者元素嵌套在其他定位元素中。position 属性设置为 relative、absolute 或 fixed。$('#myElement').css('position', 'relative');
var offset = $('#myElement').offset();$(document).ready() 确保在 DOM 完全加载后再获取位置。$(document).ready(function() {
var offset = $('#myElement').offset();
});通过以上方法,可以有效地获取和处理元素相对于浏览器的位置信息。
没有搜到相关的沙龙