DIV CSS 佈局教程網

jQuery獲取div絕對位置
編輯:JQuery常見問題     
offset() 方法返回或設置匹配元素相對於文檔的偏移(位置)。

絕對位置:
var X = $('#DivID').offset().top;
var Y = $('#DivID').offset().left;


返回第一個匹配元素的偏移坐標。
該方法返回的對象包含兩個整型屬性:top 和 left,以像素計。此方法只對可見元素有效。

語法
$(selector).offset()
實例:
<html>
<head>
<script type="text/javascript" src="http:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
x=$("p").offset();
$("#span1").text(x.left);
$("#span2").text(x.top);
});
});
</script>
</head>
<body>
<p>本段落的偏移是 <span id="span1">unknown</span> left 和 <span id="span2">unknown</span> top。</p>
<button>獲得 offset</button>
</body>
</html>




設置偏移坐標
設置所有匹配元素的偏移坐標。
語法
$(selector).offset(value)
參數value為必需。規定以像素計的 top 和 left 坐標。
可能的值:
值對,比如 {top:100,left:0}
帶有 top 和 left 屬性的對象
實例:
<html>
<head>
<script type="text/javascript" src="http:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").offset({top:100,left:0});
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>設置新的偏移</button>
</body>
</html>



使用函數來設置偏移坐標
使用函數來設置所有匹配元素的偏移坐標。
語法
$(selector).offset(function(index,oldoffset))
參數function(index,oldoffset)
規定返回被選元素新偏移坐標的函數。
index - 可選。接受選擇器的 index 位置
oldvalue - 可選。接受選擇器的當前坐標。
實例:
<html>
<head>
<script type="text/javascript" src="http:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").offset(function(n,c){
newPos=new Object();
newPos.left=c.left+100;
newPos.top=c.top+100;
return newPos;
});
});
});
</script>
</head>
<body>
<p>這是一個段落。</p>
<button>設置 p 元素的 offset 坐標</button>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved