jQuery offset()方法

jQuery offset()方法

jQuery offset() 方法用于获取第一个匹配元素的当前偏移量。

它提供了两种方法:设置或返回相对于文档的选择元素的偏移坐标。

  • 返回偏移量: 当使用此方法返回偏移量时,它返回第一个匹配元素的偏移坐标。它指定了对象的两个属性:垂直和水平像素位置。
  • 设置偏移量: 当使用此方法设置偏移量时,它设置所有匹配元素的偏移坐标。

语法:

返回偏移坐标: RETURN

$(selector).offset() 

设置偏移坐标: SET

$(selector).offset({top:value,left:value}) 

使用函数设置 偏移坐标

$(selector).offset(function(index,currentoffset)) 

jQuery offset 方法的参数

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

jQuery offset()方法示例1

让我们来举个例子来演示jQuery offset()方法。

<!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(){
        var x = $("p").offset();
        alert("Top: " + x.top + " Left: " + x.left);
    });
});
</script>
</head>
<body>
<p>You are reading this tutorial on javatpoint.com</p>
<button>Click here to return the offset coordinates of the p element</button>
</body>
</html>

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>

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程