jQuery | offset()及其示例

offset()方法是jQuery中的一个内置方法,用于设置或返回所选元素的偏移坐标。 语法:

null
$(selector).offset()
  • 参数: 参数不是必需的。
$(selector).offset({top:value, left:value})
  • 参数: 设置偏移时,该参数是必需的。
$(selector).offset( function(index, offset) )
  • 参数: 此方法使用函数设置偏移。此方法中使用的参数是可选的。index参数用于返回设置元素的位置,offset返回所选元素的坐标。

返回值: 此方法返回匹配元素的坐标。 以下示例说明了jQuery中的offset()方法: 例1: 在下面的代码中,这将返回第一个匹配元素的坐标。

html

<!DOCTYPE html>
< html >
< head >
< title >The offset Method</ title >
< script src =
</ script >
<!-- jQuery code to show the working of this method -->
< script >
$(document).ready(function() {
$("button").click(function() {
var Geek = $("p").offset();
alert("Top coordinate: " + Geek.top +
"   Left Coordinate: " + Geek.left);
});
});
</ script >
< style >
div {
width: 60%;
min-height: 150px;
padding: 20px;
font-size: 25px;
border: 2px solid green;
font-weight: bold;
color:green;
}
</ style >
</ head >
< body >
<!-- Click on paragraph -->
< div >
< p >Welcome to GeeksforGeeks!</ p >
< button >click Here!</ button >
</ div >
</ body >
</ html >


输出:

offset

例2:

html

<!DOCTYPE html>
< html >
< head >
< title >The offset Method</ title >
< script src =
</ script >
<!-- jQuery code to show the working of this method -->
< script >
$(document).ready(function() {
$("button").click(function() {
$("p").offset({top: 100, left: 140});
});
});
</ script >
< style >
div{
width: 300px;
min-height: 100px;
color:green;
font-weight: bold;
padding:20px;
font-size: 25px;
border: 2px solid green;
}
</ style >
</ head >
< body >
< div >
<!-- Click on paragraph -->
< p >Welcome to GeeksforGeeks!</ p >
< button >Click Here!</ button >
</ div >
</ body >
</ html >


输出:

offset method

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享