收藏
回答

js为什么获取不到style.left的值?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin0px;padding0px;}
        #outer{
            width300px;
            height300px;
            border1px solid #000;
            background: palegreen;
            position: relative;
        }
        #inner{
            width50px;
            height50px;
            border1px solid #000;
            background: orange;
            position: absolute;
            left0px;
            top0px;
        }
    </style>
    <script>
        window.onload=function(){
            var outer=document.getElementById("outer");
            var inner=document.getElementById("inner");
            console.log(inner.style.left)
            onkeyup=function(e){
                let keyCode=e.keyCode;  /*37,38,39,40*/
                switch(keyCode){
                    case 37:
                        console.log(inner.style.left)
                    break;
                    case 38:
                        console.log("up")
                    break;
                    case 39:
                        console.log("right")
                    break;
                    case 40:
                        console.log("down")
                    break;
                }
                


            }
        }
    </script>
</head>
<body>
    <div id="outer">
        <div id="inner"></div>
    </div>
</body>
</html>

回答关注问题邀请回答
收藏

1 个回答

  • 做你的太阳ღ₅₂₀¹³¹⁴
    做你的太阳ღ₅₂₀¹³¹⁴
    03-10
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    * {
      margin: 0px;
      padding: 0px;
    }
    #outer {
      width: 300px;
      height: 300px;
      border: 1px solid #000;
      background: palegreen;
      position: relative;
    }
    #inner {	
      width: 50px;
      height: 50px;
      border: 1px solid #000;
      background: orange;
      position: absolute;
      left: 10px;
      top: 0px;
    }
    </style>
    <script>
      window.onload = function() {
        var dom = document.getElementById("inner");
        if(window.getComputedStyle) {
          var str = document.defaultView.getComputedStyle(dom,null).left
      console.log(str);
        } else if(dom.currentStyle) { //兼容低版本ie
          console.log("ie版本 " + dom.currentStyle.left)
        }
      }
    </script>
    </head>
    <body>
      <div id="outer">
        <div id="inner"></div>
      </div>
    </body>
    </html>
    
    03-10
    赞同
    回复 1
登录 后发表内容
问题标签