欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解 javascript中offsetleft屬性的用法

 更新時間:2015年11月11日 09:12:31   投稿:mrr  
本章節(jié)通過代碼實(shí)例介紹一下offsetleft屬性的用法,需要的朋友可以做一下參考。

此屬性可以返回當(dāng)前元素距離某個父輩元素左邊緣的距離,當(dāng)然這個父輩元素也是有講究的。

(1).如果父輩元素中有定位的元素,那么就返回距離當(dāng)前元素最近的定位元素邊緣的距離。
(2).如果父輩元素中沒有定位元素,那么就返回相對于body左邊緣距離。

語法結(jié)構(gòu):

obj.offsetleft

特別說明:此屬性是只讀的,不能夠賦值。

代碼實(shí)例:

<!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è)的距離,因?yàn)閙ain元素是第一個定位父輩元素。

<!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)在距離瀏覽器左邊的距離。當(dāng)然你也可以用他給對象賦值,offset不單單只有Left 還有offsetTop offsetWidth offsetHeight 都是JS里很有用的屬性。

相關(guān)文章

最新評論