詳解 javascript中offsetleft屬性的用法
此屬性可以返回當前元素距離某個父輩元素左邊緣的距離,當然這個父輩元素也是有講究的。
(1).如果父輩元素中有定位的元素,那么就返回距離當前元素最近的定位元素邊緣的距離。
(2).如果父輩元素中沒有定位元素,那么就返回相對于body左邊緣距離。
語法結(jié)構(gòu):
obj.offsetleft
特別說明:此屬性是只讀的,不能夠賦值。
代碼實例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://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>
上面的代碼可以返回inner元素距離main元素的左側(cè)的距離,因為main元素是第一個定位父輩元素。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://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元素左側(cè)的尺寸。
此屬性具有一定的兼容性問題,具體可以參閱offsetleft兼容性簡單介紹一章節(jié)。
ps:js中的offsetLeft屬性具體有什么作用?
可以判斷一個物體的跟document的左邊距離,也就是瀏覽器左邊緣。比如你寫一個div 獲取這個div之后alert(你的div.offsetLeft)就可以看到他現(xiàn)在距離瀏覽器左邊的距離。當然你也可以用他給對象賦值,offset不單單只有Left 還有offsetTop offsetWidth offsetHeight 都是JS里很有用的屬性。
相關(guān)文章
原生JS+HTML5實現(xiàn)的可調(diào)節(jié)寫字板功能示例
這篇文章主要介紹了原生JS+HTML5實現(xiàn)的可調(diào)節(jié)寫字板功能,涉及javascript結(jié)合HTML5屬性動態(tài)操作頁面元素實現(xiàn)繪圖功能相關(guān)技巧,需要的朋友可以參考下2018-08-08JavaScript遞歸函數(shù)解“漢諾塔”算法代碼解析
這篇文章主要介紹了JavaScript遞歸函數(shù)解“漢諾塔”算法代碼解析,需要的朋友可以參考下2018-07-07swiper 解決動態(tài)加載數(shù)據(jù)滑動失效的問題
下面小編就為大家分享一篇swiper 解決動態(tài)加載數(shù)據(jù)滑動失效的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02如何設(shè)置iframe高度自適應(yīng)在跨域情況下的可用方法
iframe的高度需要根據(jù)子頁面的實際高度來進行調(diào)整,但是如果子頁面不在同一域中怎么辦?這時候腳本沒有辦法獲取到子頁面的高度,存在JavaScript跨域的問題2013-09-09