gpt4 book ai didi

javascript - 如何正确使用 CSSStyleSheet.insertRule()?

转载 作者:可可西里 更新时间:2023-11-01 02:03:04 29 4
gpt4 key购买 nike

我不知道我哪里错了:/。当我运行这段代码时,我得到的只是一个空白元素。我似乎无法让 insertRule 方法执行任何操作(甚至不产生错误)。我错过了什么吗?

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<script>
var sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");

// WebKit hack
style.appendChild(document.createTextNode(""));

// Add the <style> element to the page
document.head.appendChild(style);

return style.sheet;
})();
sheet.insertRule("\
#gridContainer {\
width: 100%;\
height: 100%;\
}\
", 0);
</script>
</body>
</html>

最佳答案

这有点令人困惑,但您的代码确实有效,只是您在返回的 XML 树中看不到插入的规则。

要验证您的代码是否有效,您可以进行两项测试:

var style = (function() {
// Create the <style> tag
var style = document.createElement("style");

// WebKit hack
style.appendChild(document.createTextNode(""));

// Add the <style> element to the page
document.head.appendChild(style);

console.log(style.sheet.cssRules); // length is 0, and no rules

return style;
})();
style.sheet.insertRule('.foo{color:red;}', 0);
console.log(style.sheet.cssRules); // length is 1, rule added
<p class="foo">
I am some text
</p>

运行上面的代码片段,您可以看到 CSS 规则确实适用。 cssRules 属性也在控制台中更改。

当浏览器扩展生成附加到 DOM 的自定义样式表时,通常会注意到这一点,并且在调试时它们在检查器中显示为空样式表。

关于javascript - 如何正确使用 CSSStyleSheet.insertRule()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930846/

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