是否可以使用 insertRule() 向 css 添加多个规则?

Kar*_*ikh 3 javascript css

您好,这是 HTML 代码

<html>
<head>
 <link rel="stylesheet" type="text/css" href="Theme.css"> 
</head>
<body>
<div>
    <textarea id="ta" onpaste="functionItalic(event)" class="foostyle2"></textarea>
</div>
<div>
    <span style="font-weight: bolder; font-size: 20px;">
        <span id="1">Karan's</span>
     </span>
    <span style="font-weight: bolder; font-size: 24px; font-style: italic;">test</span>
</div>
<script>
function functionItalic(pasteEvent)
{
var textareacont = (pasteEvent.originalEvent || pasteEvent).clipboardData.getData("text/html");
console.log(textareacont);
var styleSheetList = document.styleSheets;
document.getElementById("1").className = "foostyle";
var stringCSS = ".foostyle{font-family: Times-Roman;font-size:10pt;color:rgb(0,0,0);font-style:normal;}";
styleSheetList[0].insertRule(stringCSS, styleSheetList[0].cssRules.length);

}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当我运行这个文件时,一切正常并且样式被添加。

但是一旦我将 stringCSS 的值更改为

var stringCSS = ".foostyle{font-family: Times-Roman;font-size:10pt;color:rgb(0,0,0);font-style:normal;} .foostyle2{background: green;}";
Run Code Online (Sandbox Code Playgroud)

浏览器提供错误

SyntaxError: An invalid or illegal string was specified
styleSheetList[0].insertRule(stingCSS, styleSheetList[0].cssRules.length);
Run Code Online (Sandbox Code Playgroud)

我缺少的是通过 insertRule 添加多个类/规则是不可能的,或者我犯了一些错误?请帮忙。

ade*_*neo 7

规范指出

如果规则参数中给出了多个规则,则会因 SyntaxError 中止

那么什么是规则呢,规范中也说规则是

...包含要插入的规则的 DOMString,...其中规则指定选择器和声明,或 at 标识符和规则内容。

所以它是一个带有样式“选择器和声明”的字符串,换句话说,规则是

.selector {declaration : of_styles}
Run Code Online (Sandbox Code Playgroud)

或使用“at-标识符和规则内容”

@font-face { font-family: 'font'; src: local('font'), url(/font.ttf); }
Run Code Online (Sandbox Code Playgroud)

你正在通过它

.foostyle{font-family: Times-Roman;font-size:10pt;color:rgb(0,0,0);font-style:normal;} 
.foostyle2{background: green;}
Run Code Online (Sandbox Code Playgroud)

这是两个规则,并且如预期的那样,它会因语法错误而中止。

要解决这个问题,您必须调用insertRule()两次,每个规则调用一次