许多工具/ API提供了选择特定类或ID元素的方法.还可以检查浏览器加载的原始样式表.
但是,对于浏览器呈现元素,它们将编译所有CSS规则(可能来自不同的样式表文件)并将其应用于元素.这就是您在Firebug或WebKit Inspector中看到的内容 - 一个元素的完整CSS继承树.
如何在纯JavaScript中重现此功能而无需其他浏览器插件?
也许一个例子可以为我正在寻找的东西提供一些澄清:
<style type="text/css">
p { color :red; }
#description { font-size: 20px; }
</style>
<p id="description">Lorem ipsum</p>
Run Code Online (Sandbox Code Playgroud)
这里p#描述元素应用了两个CSS规则:红色和20像素的字体大小.
我想找到这些计算出的CSS规则源自的来源(颜色来自p规则等).
如何var(…)使用JavaScript(plain或jQuery)获取和设置CSS自定义属性(在样式表中访问的属性)?
这是我不成功的尝试:单击按钮更改常用font-weight属性,但不更改自定义--mycolor属性:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
body {
--mycolor: yellow;
background-color: var(--mycolor);
}
</style>
</head>
<body>
<p>Let's try to make this text bold and the background red.</p>
<button onclick="plain_js()">Plain JS</button>
<button onclick="jQuery_()">jQuery</button>
<script>
function plain_js() {
document.body.style['font-weight'] = 'bold';
document.body.style['--mycolor'] = 'red';
};
function jQuery_() {
$('body').css('font-weight', 'bold');
$('body').css('--mycolor', 'red');
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud) 所以我试图复制适用于一个元素的所有样式(class/id/tagName/attribute等).到目前为止,我发现我可以复制元素的计算样式,只有一个问题... couldend将它应用于其他元素; /
或diffrend复制所有样式的方法.
(这是我得到的:/) http://jsfiddle.net/8KdJd/2/
//queriks mode + minor changes to retrive the computed style
function getCS(el)
{
if (el.currentStyle)
var y = el.currentStyle;
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null);
return y;
}
function setCS(el,cs)
{
if (el.currentStyle)
{
el.currentStyle = cs;
el.style = cs;
}
else if (window.getComputedStyle)
{el.style = cs
}
}
var myLink = document.getElementById('myLink');
var anotherLink = document.getElementById('anotherLink');
var CS_myLink = getCS(myLink);
setCS(anotherLink,CS_myLink);
Run Code Online (Sandbox Code Playgroud)