学习JS——为什么我的元素没有任何样式

Learning JS - why do my elements not have any styles

我的网页出现问题

document.getElementById("btn").addEventListener("click", function(){
  var g = document.getElementById("guitar");
  console.log("Styles:", g.style.left,g.style.top, g.style.width,g.style.height, g.style.background);
});
  <html>
    <head>
      <style>
    
      .stage {
     position:relative; width:400px;height:300px;background:brown;
      }
    
      .guitar {
     position:absolute;     left:20px;     top:10px;     width:150px;     height:150px;     background:#f63f63;
      }
    
      </style>
    </head>
    <body>
    
      <input type="button" id="btn" value="Do something" />
    
      <div class="stage" id="stage">
        <div class="guitar" id="guitar" />
      </div>
    <body>
  </html>
    
   

如果您注意到最后一行代码,我指的是吉他的 g(我知道不好的命名等,我只是在这里胡说八道)。

我的问题是,当我将手表放在 g 上并展开属性并导航到样式时,有 none(样式列表中没有值)。即使背景显示为空值,但 HTML 正确呈现它。

为什么我看不到手表中的数值Window?

您的 g 元素没有任何样式 属性 ...

您可以在 'computed style' 上看到所有样式定义,因为它们是常规 css 声明,而不是通过属性定义。

试试 window.getComputedStyle(g,null).getPropertyValue("height");

这应该可以解决问题

来自https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

The HTMLElement.style property returns a CSSStyleDeclaration object that represents only the element's inline style attribute, ignoring any applied style rules.

这意味着如果您有一个元素 <div style="left: 10px;">,那么它的样式对象将包含 left 值,但如果您只有 CSS 规则 div { left: 10px; }.

如前所述,您可以使用 getComputedStyle() 来获得 CSS 应用的实际样式。