我想找到某个 div 内的所有类和 id!还有这些 css 属性!
示例:
<div class="demo">
<div class="new_class">
<p id="para">This is Demo Paragraph</p>
<a style="background:#ccc">HyperLink</a>
</div>
</div>
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
</style>
现在的问题是:我想找到演示类中使用的所有类和 ID!以及它们的 css 值(现在应用哪种样式。)。 我想找到如下结果:
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
a{background:#ccc;}
</style>
最佳答案
OP,不确定您的目的是什么,但总的来说,这可能很有用。我有一个元素,需要将一个网站的精美模板嵌入到另一个网站的页面上,该网站具有非常不同且相互冲突的样式表。我使用了一些类似于以下的代码来从原始内容中获取每个应用的样式,通过 document.styleSheets ,然后将它们全部重新应用为内联样式,这样我就可以将其放在“父”站点上,而不会与样式表发生冲突。
<强> Fiddle
JS
var selector,rule;
var result=[];
var sheets = document.styleSheets;
for (var i in sheets) {
//rules or cssRules, depending on the browser
var rules = sheets[i].rules || sheets[i].cssRules;
//iterate over every css rule in the document
for (var r in rules)
{
selector=rules[r].selectorText;
rule=rules[r].cssText;
//select demo itself, as well as all of its children
$('.demo, .demo *').each(function () {
//console.log($(this),selector);
//for each element, see if it matches the current rule. add if it does
if ($(this).is(selector))
{
result.push(rule);
}
});
}
}
console.log(result);
//result[0] .demo { height: 100px; width: 100px; background: none repeat scroll 0% 0% rgb(255, 255, 0); }
//result[1] .new_class { height: 40px; width: 40px; background: none repeat scroll 0% 0% rgb(153, 153, 153); }
//result[2] #para { color: rgb(225, 225, 225); }
当然,您必须自己调整它来执行以下操作:删除重复的样式(如果您将其应用到更大的 HTML block 时可能会出现这种情况),以及处理内联样式(这不会尝试这样做)做,但您可以从 style
属性获取它们并从那里开始工作...),也可能是计算的样式,您可以使用 getComputedStyle 获得它,正如 @Derek 的回答所示。但这应该可以帮助您入门。
关于javascript - 如何查找某个div内的所有css类及其css属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26418200/