【问题标题】:Get the list of all css styles applied to a specific element获取应用于特定元素的所有 CSS 样式的列表
【发布时间】:2016-05-11 09:56:14
【问题描述】:

有什么方法可以获取仅适用于特定 html 元素的用户定义的计算 css 样式列表。样式可以通过外部 css 文件或嵌入/内联样式以现在可用的任何方式应用。

.p1{font-size:14px; line-height:20px;}
<style>
  .p1{ line-height:18px; color:green;}
</style>
<p class="p1" style="color:red;">Some Paragraph</p>

现在我需要的列表是唯一应用于元素的用户定义计算样式,而不是由 window.getComputedStyle()

为了更准确地回答我的问题,我想提出一个场景,即我第一次访问网站,我想使用开发人员工具栏以编程方式(或通过编写一些脚本)获取唯一的用户定义样式在控制台上)。所以考虑到这种情况,我需要的最终输出应该是-

{
  'color':'red',
  'line-height' : '18px',
  'font-size' : '14px'  
}

如果需要,请纠正我的疑问或解释中的任何错误。

【问题讨论】:

  • 没有跨浏览器解决方案也可以正常使用 IE。
  • 你可能需要一个像 github.com/reworkcss/css 这样的 CSS 解析器,找出元素和继承的样式,将它们简化为一个列表,然后将其与 getComputedStyle() 返回的任何内容进行比较。听起来——我相信是——非常复杂。 @Himanshu 的回答可能会消除对解析器的需求。

标签: javascript jquery html css


【解决方案1】:

你要找的方法是:

window.getComputedStyle()

见:Mozilla Developer Network (MDN) on Window.getComputedStyle();

http://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

Window.getComputedStyle() 方法在应用活动样式表并解决这些值可能包含的任何基本计算后给出元素的所有 CSS 属性的值。


根据您问题中的标记和样式:

var para1 = document.getElementsByClassName('p1')[0];
var para1Styles = window.getComputedStyle(para1);

para1Color = para1Styles.getPropertyValue('color'); // red
para1FontSize = para1Styles.getPropertyValue('font-size'); // 14px
para1LineHeight = para1Styles.getPropertyValue('line-height'); // 20px

同样的方法还允许您通过声明第二个(可选)参数来从伪元素中提取样式属性值。

例如。

var para1AfterStyles = window.getComputedStyle(para1, ':after');

【讨论】:

  • 感谢您的帮助!但也许我的查询并没有具体针对该主题。所以我已经更新了查询,并希望再次收到您的意见或回复,因为上面的代码不符合我的预期。
【解决方案2】:

我也一直在寻找这个问题的答案。我想出了一个解决方案,但它有点骇人听闻。它确实在一定程度上解决了问题。

function getAppliedComputedStyles(element, pseudo) {
    var styles = window.getComputedStyle(element, pseudo)
    var inlineStyles = element.getAttribute('style')

    var retval = {}
    for (var i = 0; i < styles.length; i++) {
        var key = styles[i]
        var value = styles.getPropertyValue(key)

        element.style.setProperty(key, 'unset')

        var unsetValue = styles.getPropertyValue(key)

        if (inlineStyles)
            element.setAttribute('style', inlineStyles)
        else
            element.removeAttribute('style')

        if (unsetValue !== value)
            retval[key] = value
    }

    return retval
}

如果有帮助,请告诉我。

它使用 css unset 属性值,仅在现代浏览器中受支持。 https://developer.mozilla.org/en/docs/Web/CSS/unset#Browser_compatibility

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 2018-05-19
    • 2014-01-15
    • 1970-01-01
    • 2010-12-17
    • 2011-07-14
    • 1970-01-01
    • 2013-03-31
    • 2011-09-26
    相关资源
    最近更新 更多