本文執行個體講述了jQuery中offset()方法用法。分享給大家供大家參考。具體分析如下:
此方法返回或設定所匹配元素相對於document對象的位移量。
文法結構一:
複製代碼 代碼如下:
$(selector).offset()
擷取匹配元素在當前document的相對位移。
返回的對象包含兩個整型屬:top和left。
此方法只對可見元素有效。
執行個體代碼:
複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.jb51.net/" />
<title>offset()函數-雲棲社區</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
.father{
border:1px solid black;
width:400px;
height:300px;
padding:10px;
margin:50px;
}
.children{
height:150px;
width:200px;
margin-left:50px;
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(){
a=$(".children").offset();
alert("元素的位移量座標是:"+a.top+"|"+a.left+"");
})
})
</script>
</head>
<body>
<div class="father">
<div class="children"></div>
</div>
<button>擷取元素的座標</button>
</body>
</html>
以上代碼可以彈出子div相對於document的位移量。
文法結構二:
複製代碼 代碼如下:
$(selector).offset(value)
設定匹配元素相對於document對象的座標。
offset()方法可以讓我們重新設定元素的位置。這個元素的位置是相對於document對象的。
如果對象原先的position樣式屬性是static的話,會被改成relative來實現重定位。
參數列表:
| 參數 |
描述 |
| value |
規定以像素計的 top 和 left 座標。 可能的值: 1.值對,比如 {top:200,left:10}。 2.帶有top和left 屬性的對象。 |
執行個體代碼:
複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://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="http://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(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>
以上代碼同樣可以設定元素的位移,不過值是通過函數返回。
希望本文所述對大家的jQuery程式設計有所協助。