我正在尝试创建一个函数,其中:
这是我到目前为止的地方:
HTML :
<span class="slap0" data-finddeclaration="element">The great white fox</span>
<div class="description" data-writedeclaration="element">
</div>
<span class="slap1" data-finddeclaration="element">The great white fox</span>
<div class="description" data-writedeclaration="element">
</div>
<span class="slap2" data-finddeclaration="element">The great white fox</span>
<div class="description" data-writedeclaration="element">
</div>
<span class="slap3" data-finddeclaration="element">The great white fox</span>
<div class="description" data-writedeclaration="element">
</div>
JS :
function readOutCssRules() {
var dataElement = document.querySelectorAll('[data-finddeclaration="element"]');
var classRules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
var writeDataElement = document.querySelectorAll('[data-writedeclaration="element"]');
for (var i = 0; i < dataElement.length; i++) {
dataElement[i].className;
if (classRules[i].selectorText == "." + dataElement[i].className) {
console.log(classRules[i].cssText);
writeDataElement[i].innerHTML = classRules[i].cssText;
}
}
}
readOutCssRules();
但是该功能没有按预期工作。 有任何想法吗? 提前谢谢。
答案 0 :(得分:1)
您的代码正常运作。
你只需要删除for循环中的一行:
for (var i = 0; i < dataElement.length; i++) {
//dataElement[i].className; --> remove this
if (classRules[i].selectorText == "." + dataElement[i].className) {
console.log(classRules[i].cssText);
writeDataElement[i].innerHTML = classRules[i].cssText;
}
}
在改变之后它会起作用,正如你在this小提琴中看到的那样。
答案 1 :(得分:1)
检查
https://jsfiddle.net/g6tu77mg/1/
var element = classRules[i].cssText
var css= element.substring(element.lastIndexOf("{")+1,element.lastIndexOf("}"));
writeDataElement[i].innerHTML = css;
输出:
The great white fox
color: blue;
The great white fox
color: red;
The great white fox
color: yellow;