html - 内部CSS样式定义

标签 html css

有以下代码

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

警报未显示任何内容(无结果,空字符串)。 当我将样式定义移动到 body 时标签( <body style="background-color:green"> )它按预期工作 - 返回“绿色”字符串。为什么获取内部样式(style 标签内)值不起作用?

最佳答案

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

var style = window.getComputedStyle(document.getElementsByTagName("BODY")[0]);
alert(style.backgroundColor)

关于html - 内部CSS样式定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775673/

相关文章:

javascript - 当我添加更多 Material 时,我的内容不会超出一页

javascript - 修改html打印的页眉

html - Flexbox 内容显示不正确

javascript - Angular 6 - router-outlet - 使用 CSS 加载外部 HTML

css - 对齐不同 block 的子元素

html - 尝试使用 HTML 和 CSS 使按钮可点击

javascript - 使用 javascript document.addEventListener 在下一个窗口中打开选项卡

jquery - 应用于父 div 的框阴影会切断 IE 中的子 div

css - 删除某些屏幕尺寸的元素

html - flash 和显示的 div 的问题