详解 javascript中offsetleft属性的用法

  作者:bea

此属性可以返回当前元素距离某个父辈元素左边缘的距离,当然这个父辈元素也是有讲究的。 (1).如果父辈元素中有定位的元素,那么就返回距离当前元素最近的定位元素边缘的距离。 (2).如果父辈元素中没有定位元素,那么就返回相对于body左边缘距离。 语法结构: obj.offsetleft 特别说明:此属性是只读的,不能够赋值。 代码实例: <!DOCTYPE html><html><head><meta charset="utf-8"

此属性可以返回当前元素距离某个父辈元素左边缘的距离,当然这个父辈元素也是有讲究的。


(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里很有用的属性。




有用  |  无用

猜你喜欢