javascript - 尝试在 ie 中将规则添加到样式表时出现无效参数错误

标签 javascript css internet-explorer stylesheet

我试图动态删除一个规则,然后在它的位置添加一个新规则,以获得动态变化的 div innerHTML 的计算动画。

var ss = document.styleSheets ;           
for(j=0;j<ss[0].cssRules.length;j++)
if(ss[0].cssRules[j].name == "slide")
{  
ss[0].deleteRule(j);                              
break;
}  
ss[0].addRule('@keyframes slide', 'from {top:0px;} to {top:-300px;}', 0);

上面的代码应该删除一个 css 动画并插入一个新的。 问题在于“@”字符,如果我删除它代码通过,但它不是动画,因为它没有“@keyframes”标识符。我以这种方式进行此操作的原因是因为您在 ie11 的 css 中没有变量,并且您不能更改样式表 csstext!所以我想删除整个规则并插入一个新规则。 我要做的就是动态更改此规则:

@keyframes slide { 
     from {top:0px;}  
     to   {top:-100px;}
}

以这条规则为例:

@keyframes slide { 
     from {top:0px;}  
     to   {top:-300px;}
}

尝试和ie的特殊世界打交道真的很头疼!! 感谢您的帮助。

最佳答案

我已经测试了您的代码并试图找出它在 IE 中不起作用的原因。但是我找不到一个很好的理由。看起来就像您提到的那样,IE 无法读取带有@ 的关键字。我刚刚找到一个解决方法是自定义一个函数来添加属性。这是我的工作演示。

CSS

<style>
    div {
        margin-top: 500px;
        width: 100px;
        height: 100px;
        background: red;
        position: relative;
        animation: mymove 5s infinite;
    }

    @keyframes mymove {
        from {
            top: 0px;
        }

        to {
            top: 200px;
        }
    }
</style>

HTML

<script>
    function insertStyleSheetRule(ruleText) {
        let sheets = document.styleSheets;
        if (sheets.length == 0) {
            let style = document.createElement('style');
            style.appendChild(document.createTextNode(""));
            document.head.appendChild(style);
        }
        let sheet = sheets[sheets.length - 1];
        sheet.insertRule(ruleText, sheet.rules ? sheet.rules.length : sheet.cssRules.length);
    }
    insertStyleSheetRule("@keyframes mymove{from {top:0px;} to {top:-300px;}}");
    insertStyleSheetRule("div {margin-top: 500px;width: 100px;height: 100px;background: red;position: relative; animation: mymove 5s infinite;- webkit - animation: mymove 5s infinite;}");
</script>

关于javascript - 尝试在 ie 中将规则添加到样式表时出现无效参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55639624/

相关文章:

javascript - 如何使用 jQuery 克隆没有数据但只有结构的 <tr> 元素?

c# - 使用操作将表单参数发送到 Web 服务

javascript - Jquery UI resize 和 draggable 不能一起工作?

javascript - jquery ajax 在 str.replace 后不工作

javascript - 滚动时 IE 屏幕闪烁

javascript - polymer 纸图标按钮不会触发点击

javascript - 以编程方式管理 Cassandra 权限

html - 每次我将鼠标悬停在按钮上时,我的文字和图像都会移动

javascript - 三元素内联 Bootstrap

css - Edge 和 IE CSS 网格兼容性