首页 文章

如何使用Dart动态添加样式表?

提问于
浏览
5

我在Javascript中知道如何动态添加样式表 . 这可以使用以下代码完成:

var sheet = document.createElement('style');

但是当我尝试使用Dart(https://www.dartlang.org/)时,就像这样:

CssStyleSheet sheet = document.createElement('style');

然后Dart编辑器告诉我"A value of type Element cannot be assigned to a variable of type CssStyleSheet" .

我也尝试过这样:

CssStyleSheet styleSheet = new CssStyleSheet();

但那给了我警告"The class CssStyleSheet does not have a default constructor"

还有这个:

CssStyleSheet sheet = DomImplementation.createCssStyleSheet('mySheet', '');

符合"Instance member 'createCssStyleSheet' cannot be accessed using static access" .

所以我的问题是:如何在Dart中创建CssStyleSheet,这样我就可以使用像 insertRule(rule, index)deleteRule(index) 这样的方法?

亲切的问候,
亨德里克

2 回答

  • 6

    我尝试了它,它对我有用:

    import 'dart:html' as dom;
    
    main () {
      dom.document.head.append(new dom.StyleElement());
      final styleSheet = dom.document.styleSheets[0] as dom.CssStyleSheet;
      final rule = 'div { color: blue; }';
      styleSheet.insertRule(rule, 0);
    }
    
  • 6

    GünterZöchbauer的答案帮助我找到了解决方案(请参阅我对他的回答的评论) .
    这有效:

    import 'dart:html';
    
    main () {
      // create a stylesheet element
      StyleElement styleElement = new StyleElement();
      document.head.append(styleElement);
      // use the styleSheet from that
      CssStyleSheet sheet = styleElement.sheet;
    
      final rule = 'div { border: 1px solid red; }';
      sheet.insertRule(rule, 0);
    }
    

相关问题