offsetLeft 回傳目前元素距離某個父層元素左邊緣的距離,但「某個父層」到底是誰,取決於祖先元素有沒有設定定位:
obj.offsetLeft
特別注意:此屬性唯讀,不能賦值。想改變位置請改用 style.left。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="https://www.softwhy.com/" /> <title>螞蟻部落</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } #main{ width:300px; height:300px; background:red; position:absolute; left:100px; top:100px; } #box{ width:200px; height:200px; background:blue; margin:50px; overflow:hidden; } #inner{ width:50px; height:50px; background:green; text-align:center; line-height:50px; margin:50px; } </style> <script type="text/javascript"> window.onload=function(){ var inner=document.getElementById("inner"); inner.innerHTML=inner.offsetLeft; } </script> </head> <body> <div id="main"> <div id="box"> <div id="inner"></div> </div> </div> </body> </html>
#main 設了 position:absolute,是第一個定位祖先,所以 #inner 的 offsetLeft 是相對 #main 計算出來的。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="https://www.softwhy.com/" /> <title>螞蟻部落</title> <style type="text/css"> *{ margin: 0px; padding: 0px; } #main{ width:300px; height:300px; background:red; margin:100px; } #box{ width:200px; height:200px; background:blue; overflow:hidden; } #inner{ width:50px; height:50px; background:green; text-align:center; line-height:50px; margin:50px; } </style> <script type="text/javascript"> window.onload=function(){ var inner=document.getElementById("inner"); inner.innerHTML=inner.offsetLeft; } </script> </head> <body> <div id="main"> <div id="box"> <div id="inner"></div> </div> </div> </body> </html>
這次所有祖先都沒有定位,於是回傳的是 #inner 相對 body 左側的距離。
此屬性存在跨瀏覽器的相容性細節(尤其是舊版 IE),可參考 offsetLeft 相容性說明。
最常見的用途是取得元素相對文件(近似於瀏覽器邊緣)的距離。取得元素後 alert 一下它的 offsetLeft,就能知道它目前離左邊多遠。除了 offsetLeft,offsetTop、offsetWidth、offsetHeight 這一組 offset 家族屬性在處理尺寸與定位計算時都很好用,值得一起熟悉。