首頁 > web前端 > js教程 > 主體

詳解 javascript中offsetleft屬性的用法_javascript技巧

WBOY
發布: 2016-05-16 15:32:44
原創
1761 人瀏覽過

此屬性可以傳回目前元素距離某個父輩元素左邊緣的距離,當然這個父輩元素也是有講究的。

(1).如果父輩元素中有定位的元素,那麼就傳回距離當前元素最近的定位元素邊緣的距離。
(2).如果父輩元素中沒有定位元素,那麼就傳回相對於body左邊緣距離。

語法結構:

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元素的左邊的距離,因為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元素左側的尺寸。

此屬性有一定的相容性問題,具體可以參考offsetleft相容性簡單介紹一章節

ps:js中的offsetLeft屬性具體有什麼作用?

可以判斷一個物體的跟document的左邊距離,也就是瀏覽器左邊緣。例如你寫一個div 取得這個div之後alert(你的div.offsetLeft)就可以看到他現在距離瀏覽器左邊的距離。當然你也可以用他來賦值,offset不單單只有Left 還有offsetTop offsetWidth offsetHeight 都是JS裡很有用的屬性。

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!