浅谈jQuery的offset()方法及示例分享

2020-05-19 07:43:44易采站长站整理

语法结构三:

使用函数的返回值来设置偏移坐标:

$(selector).offset(function(index,oldoffset))
参数列表:

参数 描述
function(index,oldvalue) 规定返回被选元素新偏移坐标的函数:
index – 可选。元素的索引。
oldvalue – 可选。当前坐标。

实例代码:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<style type="text/css">
.father{
border:1px solid black;
width:400px;
height:300px;
}
.children{
height:150px;
width:200px;
background-color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".children").offset(function(a,b){
var newpoint= new Object();
newpoint.top=b.top+50;
newpoint.left=b.left+50;
return newpoint;
})
})
})
</script>
</head>
<body>
<div class="father">
<div class="children"></div>
</div>
<button>点击设置偏移量</button>
</body>
</html>

以上代码同样可以设置元素的偏移,不过值是通过函数返回。

以上所述就是本文的全部内容了,希望大家能够喜欢。