m0_46602893 2021-04-16 13:06 采纳率: 91.5%
浏览 34
已结题

js关于下面代码的问题

<!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>
            #box{background-color: black;};
            .box1{height: 600px;}
            /* 为啥.box1样式出不来? */
      </style>
      <script>
            window.onload = function(){
                  var oDiv = document.getElementById("box");
                  alert(oDiv.currentStyle['height'])
                  alert(getComputedStyle(oDiv)["height"])
                  //为啥同时两个alert的时候不能alert出第一个?
                  // alert (getStyle("height", oDiv))

            }
            // function getStyle(x, y){
            //       return y.currentStyle ? y.currentStyle[x]:getComputedStyle(y)[x]
            // }
            /* 这个函数的node和cssstyle都只是语义化标签,并没有给他们赋值,为什么能够说node就是一个标签下面的,cssstyle就是与之对应的样式? */


      </script>


</head>
<body>
      <div id='box' style='width: 300px; background-color: red' class='box1'></div>
</body>
</html>

问题1:上面这段代码中为什么设置的.box1{height: 600px;}高度无法显示?

问题2:

alert(oDiv.currentStyle['height'])

 alert(getComputedStyle(oDiv)["height"])

我同时alert上面这两段代码的时候为什么在谷歌浏览器上显示不出来?只有当我把alert(oDiv.currentStyle['height'])注释掉下面的alert(getComputedStyle(oDiv)["height"])才能显示?

  • 写回答

3条回答 默认 最新

  • 子幽 2021-04-16 13:53
    关注

    1、#box{background-color: black;};后面多了个分号,

    2、currentStyle只有 IE 和 Opera 支持使用 currentStyle获取 HTMLElement的计算后的样式,其他浏览器中不支持。

    3、

    var oDiv = document.getElementById("box");
    var currentStyle = '';
    if(oDiv.currentStyle){
    	currentStyle = oDiv.currentStyle.height;
    }else{
    	currentStyle = window.getComputedStyle(oDiv).height;
    }
    alert(currentStyle)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 9月4日
  • 已采纳回答 8月27日

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探