我想动态更改页面上某些文本的CSS样式(背景颜色)。为此,我试图改变CSSRule。因为,对于所需的样式,存在大约10个CSSRule,我使用selectedText访问所需的CSSRule。以下是代码:
changeRule() {
let stylesheet: CSSStyleSheet = <CSSStyleSheet>this.stylesheet.sheet;
let ruleLength: any = <CSSStyleSheet>this.stylesheet.sheet.cssRules.length;
console.log(ruleLength)
for(let i = 0; i < ruleLength; i++) {
let currentTag: any = this.stylesheet.sheet.cssRules[i].selectorText as CSSStyleSheet
let chosenTag: any = (`#text `+`[data-tag-id="${this.selectedTag.id}"]`)
if(currentTag === chosenTag) {
console.log("Rule matched");
console.log(<CSSStyleSheet>this.stylesheet.sheet.cssRules[i].style.backgroundColor);
let changedTag: any = <CSSStyleDeclaration>this.stylesheet.sheet.cssRules[i].style.backgroundColor
changedTag = "initial";
break;
}
}
console.log(<CSSStyleSheet>this.stylesheet.sheet)
}
但执行此功能后,相应的CSSRule没有变化。 BackgroundColor没有得到更新。此外,我收到cssRules [i]的编译时错误为&#34;属性样式和样式#34;上没有属性cssRules。我使用angular2和typescript
有人可以为我推荐一些东西吗?
答案 0 :(得分:0)
您正在更新变量,而不是规则属性。变化
let changedTag: any = <CSSStyleDeclaration>this.stylesheet.sheet.cssRules[i].style.backgroundColor
changedTag = "initial";
到
<CSSStyleDeclaration>this.stylesheet.sheet.cssRules[i].style.backgroundColor = "initial";
JavaScript示例(使用"yellow"
代替"initial"
):
function changeRule() {
let stylesheet = this.stylesheet.sheet;
let ruleLength = this.stylesheet.sheet.cssRules.length;
console.log(ruleLength)
for (let i = 0; i < ruleLength; i++) {
let currentTag = this.stylesheet.sheet.cssRules[i].selectorText
let chosenTag = (`#text ` + `[data-tag-id="${this.selectedTag.id}"]`)
if (currentTag === chosenTag) {
console.log("Rule matched");
console.log(this.stylesheet.sheet.cssRules[i].style.backgroundColor);
this.stylesheet.sheet.cssRules[i].style.backgroundColor = "yellow";
break;
}
}
console.log(this.stylesheet.sheet)
}
setTimeout(changeRule.bind({
stylesheet: {
sheet: findSheet()
},
selectedTag: {
id: "foo"
}
}), 1000);
// In case stack snippets move the sheet around:
function findSheet() {
var sheets = Array.prototype.slice.call(document.styleSheets);
var sheet;
sheets.some(function(s) {
if (s.cssRules[0].selectorText == '#text [data-tag-id="foo"]') {
sheet = s;
return true;
}
});
return sheet;
}
#text [data-tag-id="foo"] {
color: red;
background-color: grey;
}
<div id="text">
<div data-tag-id="foo">This is foo</div>
<div data-tag-id="bar">This is bar</div>
</div>