详解 javascript中offsetleft属性的用法
此属性可以返回当前元素距离某个父辈元素左边缘的距离,当然这个父辈元素也是有讲究的。
(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里很有用的属性。
谈谈对offsetleft兼容性的理解
关于此属性的基本用法可以参阅offsetleft属性用法详解一章节。此属性具有一定的兼容性问题,那就是在IE7浏览器中,它的返回值是想对于最近的父辈元
轻松实现javascript数据双向绑定
双向数据绑定指的是当对象的属性发生变化时能够同时改变对应的UI,反之亦然。换句话说,如果我们有一个user对象,这个对象有一个name属性,无论何
window.setInterval()方法的定义和用法及offsetLeft与style.left的区别
定义和用法setInterval()方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。setInterval()方法会不停地调用函数,直到clearInterval()被调用或窗口被
标签:元素,距离,属性,父辈,边缘