【问题标题】:Window.getComputedStyle does not show inline styleWindow.getComputedStyle 不显示内联样式
【发布时间】:2017-03-03 21:10:48
【问题描述】:

我有这样的简单 html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <svg id="svg" viewBox="0 0 594 600" preserveAspectRatio="xMinYMin meet">
            <rect id="rect" fill="#98df8a" style="width: 100px; height: 100px;">
            </rect>
        </svg>
    </body>
</html>

当我使用:window.getComputedStyle(document.getElementById('rect')) 时,我得到 widthheight 的值都是 auto 而不是 100px,就像我预期的那样。

这是应该的吗?如果是这样,我怎样才能让它返回 100px ?

我需要这个函数将我在外部 css 中定义的所有样式转换为 svg 元素的内联样式属性,以便我以后可以导出它。

【问题讨论】:

    标签: javascript css svg


    【解决方案1】:

    您可以只使用document.getElementById('rect').style.heightdocument.getElementById('rect').style.width,如果您想处理任意样式列表,如下所示:

    var exportStyleKeys = ['width', 'height'];
    var rect = document.getElementById('rect');
    var exportStyles = exportStyleKeys.reduce((styles, styleKey) => {
      styles[styleKey] = rect.style[styleKey];
      return styles;
    }, {});
    

    JSFiddle

    【讨论】:

      【解决方案2】:

      window.document.getElementById('rect').style.width 将返回内联 CSS 宽度属性。

      试试爆破码

      var rect = window.document.getElementById('rect');
      console.log(rect.style.width);
      <!DOCTYPE html>
      <html lang="en">
          <head>
              <meta charset="UTF-8">
              <title></title>
          </head>
          <body>
              <svg id="svg" viewBox="0 0 594 600" preserveAspectRatio="xMinYMin meet">
                  <rect id="rect" fill="#98df8a" style="width: 100px; height: 100px;">
                  </rect>
              </svg>
          </body>
      </html>

      【讨论】:

        猜你喜欢
        • 2022-11-23
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        • 2016-02-14
        • 1970-01-01
        • 2014-06-27
        • 2014-03-21
        • 2021-07-01
        相关资源
        最近更新 更多