【问题标题】:Javascript get CSS style for IDJavascript 获取 ID 的 CSS 样式
【发布时间】:2012-02-16 12:20:20
【问题描述】:

我希望能够从网页上未使用的 CSS 元素获取样式。例如,这是页面:

<html>
<head>
<style type="text/css">
#custom{
background-color: #000;
}
</style>
</head>

<body>
<p>Hello world</p>
</body>
</html>

如您所见,ID 'custom' 有一个值,但未在文档中使用。我想在页面中不使用“自定义”的所有值。我最接近的是:

el = document.getElementById('custom');
var result;
var styleProp = 'background-color';
if(el.currentStyle){
    result = el.currentStyle[styleProp];
    }else if (window.getComputedStyle){
    result = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
    }else{
    result = "unknown";
}

【问题讨论】:

  • 您尝试重新实现 CSS 类有什么特别的原因吗?请告诉我们您想要的最终结果,我们可以帮助您实现目标。

标签: javascript css styles


【解决方案1】:

创建一个具有给定 ID 的新元素并将其附加到文档中。然后只需读取值并删除元素。

例子:

var result,
    el = document.body.appendChild(document.createElement("div")),
    styleProp = 'background-color',
    style;

el.id = 'custom';
style = el.currentStyle || window.getComputedStyle(el, null);
result = style[styleProp] || "unknown";

// Remove the element
document.body.removeChild(el);

【讨论】:

    【解决方案2】:

    我认为答案不是很好,因为它需要向 DOM 添加元素,这可能会破坏您正在尝试做的事情或造成视觉故障。

    使用 document.styleSheets 我认为您可以获得侵入性较小的解决方案。 (见here

    尝试类似:

    var result;
    var SS = document.styleSheets;
    for(var i=0; i<SS.length; i++) {
        for(var j=0; j<SS[i].cssRules.length; j++) {
            if(SS[i].cssRules[j].selectorText == "#custom") {
                result = SS[i].cssRules[j].style;
            }
        }
    }
    

    这应该给你一个对象,它将包含所有样式作为键。请记住,如果在样式表中重新声明样式,您可能需要更复杂一点的算法。

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多