内部css样式定义

Mul*_*n81 2 html css

有以下代码

  <head>
    <style>
        body { background-color:green; }
    </style>            
  </head>
  <body>
    <script>
      alert(document.getElementsByTagName("BODY")[0].style.backgroundColor);
    </script>
  </body>
Run Code Online (Sandbox Code Playgroud)

警报没有显示任何内容(没有结果,空字符串).当我将样式定义移动到bodytag(<body style="background-color:green">)时,它按预期工作 - 返回"green"字符串.为什么不使内部样式(style标记内)值起作用?

t.n*_*ese 5

.style元素的属性显示由style属性设置或直接分配给元素属性但不是计算样式(HTMLElement.style)的样式.为此,你必须使用Window.getComputedStyle()

var style = window.getComputedStyle(document.getElementsByTagName("BODY")[0]);
alert(style.backgroundColor)
Run Code Online (Sandbox Code Playgroud)