jQuery中offset()方法用法实例

2020-05-22 21:58:22易采站长站整理

实例代码:


<!DOCTYPE html>
<html>
<head>
<meta charset=” utf-8″>
<meta name=”author” content=”//www.jb51.net/” />
<title>offset()函数-软件开发网</title>
<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({top:100,left:100})
  })
})
</script>
</head>
<body>
<div class=”father”>
  <div class=”children”></div>
</div>
<button>点击设置偏移量</button>
</body>
</html>

以上代码可以设置div相对于document的偏移量。

语法结构三:

使用函数的返回值来设置偏移坐标:
$(selector).offset(function(index,oldoffset))

参数列表:

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

实例代码:


<!DOCTYPE html>
<html>
<head>
<meta charset=” utf-8″>
<meta name=”author” content=”//www.jb51.net/” />
<title>offset()函数-软件开发网</title>
<style type=”text/css”>
.father{
  border:1px solid black;
  width:400px;
  height:300px;
}
.children{
  height:150px;
  width:200px;
  background-color:green;