gpt4 book ai didi

javascript - CSSRule 未使用新的背景颜色值 typescript 进行更新

转载 作者:行者123 更新时间:2023-11-28 04:35:13 24 4
gpt4 key购买 nike

我想动态更改页面上某些文本的 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] 的编译时错误,因为“样式表类型上不存在属性 cssRules”。我正在使用带有 typescript 的 angular2

有人可以为此建议我一些东西吗?

最佳答案

您更新的是变量,而不是规则属性。变化

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>

关于javascript - CSSRule 未使用新的背景颜色值 typescript 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com