素材牛VIP会员
原生JS无法输出dom元素的left值是怎么回事?
 二***了  分类:JavaScript  人气:1090  回帖:7  发布于6年前 收藏

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        *{
            margin:0;
            padding:0;
        }
        .outer{
            width: 300px;
            height: 300px;
            border: 1px solid #000;
            margin-left: 100px;
        }
        .outer .inner{
            width: 100px;
            height: 100px;
            background-color: skyblue;
            position: absolute;
            left: 0;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner"></div>
    </div>
    <script type="text/javascript">
        var i = document.querySelector(".inner");
        i.style.backgroundColor = "red";
        console.log(i.style.left);
    </script>
</body>
</html>

left值可以获取到,可以写,但是输出不了left的值,显示的是空白的,这是怎么回事呢?

 标签:cssjavascript

讨论这个帖子(7)垃圾回帖将一律封号处理……

Lv3 码奴
xi***xu 职业无 6年前#1

你是认真的? 完全可以输出啊.. 是不是被你console.log 过滤掉了

Lv7 码师
亡***师 JS工程师 6年前#2

我猜题主说的是先console.log(i.style.left)无法获取值,
设置之后又可以获取到了。
这么获取:document.defaultView.getComputedStyle(i, null)['left']

Lv3 码奴
凤***奇 职业无 6年前#3

?.?
我试了下可以输出

Lv6 码匠
lo***ou 职业无 6年前#4

你的意思是没设置就获取不了吧,因为style.left只能获取行间的样式(html 里写style),你写在css里是获取不了的,要获取用getComputedStyle,ie的话用currentStyle

  //i.style.left = "200px";
  console.log(i.style.left); // 获取不了
console.log(getElementStyle(i,"left"));
function getElementStyle(obj,attr){
  if(obj.currentStyle){
    return obj.currentStyle[attr];
  }else{
   return getComputedStyle(obj,false)[attr];   //第二个参数是伪类
  }
}
Lv1 新人
编***魔 职业无 6年前#5

i.style.left = 200 + "px";

Lv1 新人
何***孽 软件测试工程师 6年前#6

应该是可以输出的吧。
建议使用getComputedStyle(i, null).left替代i.style.left

Lv1 新人
闪***星 UI设计师 6年前#7

道友,这玩笑不好开,请打开控制台认真看一下,这是复制你的代码运行结果

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取