javascript之style.left和offsetLeft的区别

来源:互联网 发布:免费视频格式转换软件 编辑:程序博客网 时间:2024/06/04 23:20

offsetLeft取到的值是数值型的,只能取值,不能赋值。

style.left在取值的时候要事先定义好,否则取到的值为空值,不仅仅可以取值,而且还可以赋值,取到的值为字符串类型的。  demo代码如下:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><style type="text/css">* {margin: 0;padding: 0;}.box {width: 600px;height: 600px;margin: 20px;padding: 20px;border: 1px solid #000;position: absolute;}.box1 {width: 400px;height: 400px;margin: 20px;padding: 20px;border: 1px solid #000;}.box2 {width: 100px;height: 100px;margin: 20px;padding: 20px;border: 1px solid #000;}</style></head><body><div class="box" id="box"><div class="box1" id="box1" style="left:20px;"><div class="box2" id="box2"></div></div></div><script type="text/javascript">var box2 = document.getElementById("box2");var box = document.getElementById("box");var box1 = document.getElementById("box1");console.log(box1.offsetLeft);//offsetLeft是相对于有定位盒子的距离console.log(box1.style.left);//style.left的值事先要定义好,否则取到的值为空值。box1.style.left = "30px";console.log(box1.style.left);console.log(box2.offsetParent);console.log(typeof(box1.offsetLeft))</script></body></html>


原创粉丝点击