在javascript中经常遇到style.left和offsetLeft,那么它们有什么区别呢?今天我们来分析下
offsetLeft:获取当前元素相对于父元素的左侧偏移量,比如该元素设置为relative;left: -10px;那么它的offsetLeft返回值是-10,而它的style.left还是为空,因为style.left只有行内设置的样式才有效;
style.left:获取当前元素的行内样式的值;
区别在于:
1. style.left 返回的是字符串,如28px,offsetLeft返回的是数值28
,如果需要对取得的值进行计算,还用offsetLeft比较方便。
2. style.left是读写的,offsetLeft是只读的,所以要改变div的位置,只能修改style.left。
3. style.left的值需要事先定义并且定义在标签的行内,否则取到的值为空。如果定义在css里,style.left的值仍然为空。offsetLeft则仍然能够取到,无需事先定义div的位置。