将多个 CSS 规则插入样式表
-
21-12-2019 - |
题
好的,所以我需要向样式表添加规则,但它也需要跨浏览器,所以我需要多个规则。
现在我可以用一行来让一个工作(Chrome)。
但是,我找不到任何文档或与多行相关的任何内容。
这个想法是使用浏览器前缀添加多个 CSS 动画,只是为了增加乐趣。
这就是我想要做的(我正在 Chrome 中调试):
styleSheet.insertRule("@-webkit-keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} }", styleSheet.cssRules.length);
styleSheet.insertRule("@-moz-keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} }", styleSheet.cssRules.length);
styleSheet.insertRule("@-ms-keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} }", styleSheet.cssRules.length);
styleSheet.insertRule("@keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} }", styleSheet.cssRules.length);
然后我需要为每个动画添加浏览器前缀:
document.getElementById('starsColoured').style.webkitAnimationName = "userScore";
document.getElementById('starsColoured').style.mozanimationName = "userScore";
document.getElementById('starsColoured').style.MSAnimationName = "userScore";
document.getElementById('starsColoured').style.animationName = "userScore";
它不起作用,我并不感到惊讶,我只是不知道添加多个的实际方法。特别是当我尝试将前缀动画名称添加到元素时。
我尝试将所有规则放入一行,如下所示:
styleSheet.insertRule("@-webkit-keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} } @-moz-keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} } @-ms-keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} } @keyframes userScore { 0% { width: 0px; } 100% {width: " + (monkeyScore * 20) + "px;} }", styleSheet.cssRules.length);
再次不幸的是,这给了我以下错误:
Uncaught SyntaxError: Failed to execute 'insertRule' on 'CSSStyleSheet': Failed to parse the rule '@-webkit-keyframes userScore { 0% { width: 0px; } 100% {width: 380px;} } @-moz-keyframes userScore { 0% { width: 0px; } 100% {width: 380px;} } @-ms-keyframes userScore { 0% { width: 0px; } 100% {width: 380px;} } @keyframes userScore { 0% { width: 0px; } 100% {width: 380px;} }'.
如果我尝试将它们作为单独的规则,则会收到以下错误:未捕获的语法错误:无法在“CSSStyleSheet”上执行“insertRule”:无法解析规则 '@-moz-keyframes userScore { 0% { width:0 像素;} 100% {宽度:380 像素;} }'。
我在 FireFox 中尝试,收到以下错误,与第一个 insertRule 行(Chrome)相关:
SyntaxError: An invalid or illegal string was specified
就是这样。
任何帮助将非常感激!
如果可以的话,我会尽量避免使用 jQuery。
我确信任何多行文档也会对我和其他人有所帮助。
提前致谢
解决方案
刚刚修改世代odicetagcode标签?
<style id="custom-styles"></style>
<script>
var red = '#f00';
document.getElementById('custom-styles').innerHTML = 'body { color: ' + red + '; }';
</script>
.
其他提示
您可以插入带有数据 URI 的新样式表链接。假设你的CSS规则在一个变量中 css
, , 然后:
head = document.getElementsByTagName('head')[0];
stylesheet = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'data:text/css,' + escape(css); // IE needs this escaped
head.appendChild(link);
这至少在最新的 Chrome、Firefox 和 IE 中有效。
或者,您可以使用以下命令一一添加规则 insertRule
并将每个添加简单地包装在 try
块,以便忽略前缀规则引发的错误。
解析失败,因为您在样式名称中有'@'字符。 尝试用'_'删除'@'或删除它,它将工作。
不隶属于 StackOverflow