Javascript 如何在某个div中找到所有css类及其css属性?
我想找到某个div中的所有类和ID!还有这些css属性 例如:Javascript 如何在某个div中找到所有css类及其css属性?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我想找到某个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:1
<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>
这是演示段落
超链接
.演示{
高度:100px;宽度:100px;背景:#FF0;
}
.new#u class{高度:40px;宽度:40px;背景:#999;}
#段落{颜色:#e1e1;}
现在的问题是:我想找到演示类中使用的所有类和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>
.演示{
高度:100px;宽度:100px;背景:#FF0;
}
.new#u class{高度:40px;宽度:40px;背景:#999;}
#段落{颜色:#e1e1;}
a{背景:#ccc;}
要查找所有现有的id
,请尝试:
var ids = [];
$(".demo *").each(function(){ this.id && ids.push(this.id); });
console.log(ids);
对类
或其他任何内容执行相同的操作
但是,要获得预期的输出,必须首先获取每个元素定义的CSS样式。应该包括哪一个<默认情况下,code>p获取边距和填充。这些也包括在内吗?您还需要深入研究所有CSS声明,以找到应用的样式,这几乎是不可能做到的
比如说,
<div class="yellow"></div>
<style>
div.yellow:not(.blue){
background: yellow;
}
</style>
黄色分区:非(.blue){
背景:黄色;
}
如何获取
标记的背景.style.background
?不,它返回“
。现在,您必须使用document.styleSheets
来研究CSS声明,以查看哪个声明适用。您甚至如何检查规则div.yellow:not(.blue)
是否与您的元素匹配?祝你好运。(可能有一些库可以做这类事情,或者您甚至可以将jQuery的内部选择器引擎与.is
一起使用,尽管它与CSS中的不同)另一件您可以做的事情是尝试getComputedStyle
。它为您提供了甚至不在您的声明中的每一个计算样式。因此,您尝试执行的操作是不可能执行的。(我甚至不知道你在做什么。)OP,不确定你的目的是什么,但总的来说,这是有用的。我有一个项目,我需要将一个奇特的模板从一个站点嵌入到另一个站点的页面上,该页面的样式表非常不同且相互冲突。我使用了一些类似于下面的代码,通过从原始内容中获取每个应用的样式,然后将它们全部作为内联样式重新应用,这样我就可以将其放在“父”站点上,而不会与样式表冲突
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块时会出现的重复样式,以及处理内联样式(这并不尝试这么做,但您可以从
style
属性获得它们,然后从那里开始工作…),还有可能是计算的风格,你可以通过@Derek的答案得到。但这应该让您开始了。到目前为止您做了哪些尝试?使用$(“.demo”).children()然后遍历所有对象以检索单个id、类和样式属性。但是,所有输出都将使用javascript,而不是您期望的样式标记。此外,您将无法区分内联样式和其他样式。