设置自定义样式属性在 IE11 中不起作用

Posted

技术标签:

【中文标题】设置自定义样式属性在 IE11 中不起作用【英文标题】:Set custom style attribue doesn't work in IE11 【发布时间】:2020-09-04 11:35:50 【问题描述】:

我有这个简单的 javascript 代码来更改自定义 CSS 属性

var root = document.documentElement;
root.style.setProperty("--custom-bg", "#4f5357");

这在 Firefox Google Chrome 中运行良好,但在 IE 11 中无法运行,也尝试过

root['--custom-bg'] = "#4f5357";
root.attr("--custom-bg", "#4f5357");
root.style['--custom-bg'] = "#4f5357";

他们都没有工作。

【问题讨论】:

【参考方案1】:

IE11支持css自定义属性,因此不支持setProperty这个方法。

查看此css-vars-ponyfill,它旨在添加基本支持。

【讨论】:

【参考方案2】:

回复:Workaround for CSS variables in IE?

这对我来说是最好的解决方案,无需安装:

https://www.npmjs.com/package/ie11-custom-properties

将此复制到您的 html 的头部:

<script>window.MSInputMethodContext && document.documentMode && document.write('<script src="https://cdn.jsdelivr.net/gh/nuxodin/ie11CustomProperties@4.1.0/ie11CustomProperties.min.js"><\x2fscript>');</script> 

【讨论】:

以上是关于设置自定义样式属性在 IE11 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章