尝试使用typescript插入css规则时CSSStyleSheet类型问题

时间:2017-01-02 23:50:38

标签: css typescript stylesheet

我尝试使用基于https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript的typescript插入css规则。无法识别方法insertRule。我有以下错误:

Type 'StyleSheet' is not assignable to type 'CSSStyleSheet'. Property 'cssRules' is missing in type 'StyleSheet'.

这是我的代码:

let stylesheet: CSSStyleSheet = document.styleSheets[0];
stylesheet.insertRule(".scroll-content { overflow: hidden;}",0);

我正在使用离子2和角度2。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

尝试使用此代码段来定义从this answer略微修改的样式表。

if (document.styleSheets[0].cssRules)
    let stylesheet: CSSStyleSheet = document.styleSheets[0].cssRules[0];
else if (document.styleSheets[0].rules)
    let stylesheet: CSSStyleSheet = document.styleSheets[0].rules[0];

答案 1 :(得分:0)

基本上,您需要在检索当前样式表之后立即将该var转换为CSSStyleSheet

此代码将为您工作:

let stylesheet= document.styleSheets[0];
(stylesheet as CSSStyleSheet).insertRule(".scroll-content { overflow: hidden;}",0);