作业中用到了style.left和offsetLeft,想知道这俩有什么区别,现在记录下:
别人说offsetLeft是指相对于父级元素的左边位置,style.left是指相对于有定位属性的父级元素的左边位置,别人说的没懂,干脆alert这俩东西看看弹出来什么。
实验出来offsetLeft弹出来是元素所在的位置的坐标值,不错是我想取值的东西;而style.left弹出来是空的,什么东西都没有,奇怪写css时都用的left,没用过offsetLeft。哦对了!别人说style.left针对要有定位属性,那在元素样式中加入position: relative;弹出来还是空的!又查,发现有人说style.left属性写在元素标签内才能弹出东西(也就是内嵌样式),试一试成功了同时也发现弹style.left出来数值还带有px,弹offsetLeft出来只是数值,那么在js中如果要计算还是用offsetLeft比较好,因为offsetLeft的值是number类型。
当我想改变元素位置让元素移动时,就要用style.left,像写css样式那样元素位置移动是设置的数值要带有px。
那么offsetLeft就是元素左边到包裹这个元素的大盒模的左边的距离;不过style.left也是元素左边到包裹这个元素的大盒模的左边的距离,一般两个属性的值是一样的,但是当元素有marging值时,offsetLeft会把marging值算在内,而style.left则不会