Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

jQuery offset()

jQuery offset()方法用于获取第一个匹配元素的当前偏移量。
它提供了两种方法:设置或返回所选元素相对于文档的偏移坐标。
要返回偏移量::使用此方法返回偏移量时,它将返回FIRST匹配元素的偏移量坐标。它指定对象的两个属性:像素的顶部和左侧位置。 设置偏移量::使用此方法设置偏移量时,它将设置所有匹配元素的偏移量坐标。
语法:
返回偏移坐标:
$(selector).offset()
设置,偏移坐标:
$(selector).offset({top:value,left:value})
使用功能 SET 偏移坐标:
$(selector).offset(function(index,currentoffset))

jQuery偏移量方法的参数

参数 说明
{top:value,left:value} 设置偏移量时是必填参数。它以像素为单位指定顶部和左侧坐标。
function(index,currentoffset) 这是一个可选参数。它指定一个函数,该函数返回包含顶部和左侧坐标的对象。 索引:它返回元素在集合中的索引位置。 当前偏移量:它返回所选元素的当前坐标。

jQuery offset()方法的示例

让我们以一个示例来演示jQuery offset()方法。
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var x = $("p").offset();
        alert("Top: " + x.top + " Left: " + x.left);
    });
});
</script>
</head>
<body>
<p>You are reading this tutorial on lidihuo.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html>
输出:

You are reading this tutorial on lidihuo.com

jQuery offset()示例2

<!DOCTYPE html>
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var offset = $(this).offset();
$("#lresult").html("left offset: <span>" + offset.left + "</span>.");
$("#tresult").html("top offset: <span>" + offset.top + "</span>.");
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left;}
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="lresult"> </span>
<span id="tresult"> </span>
<div style="background-color:#7fffd4"></div>
<div style="background-color:#a52a2a"></div>
<div style="background-color:#7fff00"></div>
<div style="background-color:#ff1493"></div>
</body>
</html>
输出:

Click on any square:

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4