DIV CSS 佈局教程網

深入解析 jQuery offset() 方法與三種用法範例
編輯:關於JavaScript     

offset() 是什麼?

這個方法用來取得或設定「所選元素相對於 document 的偏移量」,也就是元素距離文件左上角的座標,與 position() 取得「相對於定位父元素」的偏移不同,兩者經常被搞混。

用法一:取得偏移量

 $(selector).offset() 

不帶參數時會回傳一個物件,內含 top 與 left 兩個整數屬性。要注意的是,此方法只對「可見元素」有效,元素若被隱藏則取不到正確數值。

 <!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <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 計算的。有個容易忽略的細節:如果元素原本的 position 樣式是 static,jQuery 會自動把它改成 relative,才能完成重新定位。

參數可以是值對(如 {top:200, left:10}),也可以是帶有 top 與 left 屬性的物件。

 <!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({top:100,left:100}) }) }) </script> </head> <body> <div class="father"> <div class="children"></div> </div> <button>點擊設置偏移量</button> </body> </html> 

用法三:用函式回傳值設定

 $(selector).offset(function(index,oldoffset)) 

傳入函式時,參數 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> 

三種寫法效果一致,差別只在於座標值是寫死的、傳入的,還是動態計算出來的。實務上做浮動提示框、拖曳定位時,多半會搭配 offset() 取得觸發元素的座標再往上加偏移,這也是它最常見的用法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved