How do I dynamically add a stylesheet using Dart?

梦想与她 提交于 2019-11-27 03:36:10

问题


I know in Javascript how to dynamically add a stylesheet. This can be done using the following code:

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

But when I try the same using Dart (https://www.dartlang.org/), like this:

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

Then the Dart-editor tells me "A value of type Element cannot be assigned to a variable of type CssStyleSheet".

I also tried it like this:

CssStyleSheet styleSheet = new CssStyleSheet();

But that gives me the warning "The class CssStyleSheet does not have a default constructor"

And this:

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

Gives met "Instance member 'createCssStyleSheet' cannot be accessed using static access".


So my question is: how do I create a CssStyleSheet in Dart, such that I can use methods like insertRule(rule, index) and deleteRule(index)?

Kind regards,
Hendrik


回答1:


I tried it and it worked for me:

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);
}



回答2:


The answer of Günter Zöchbauer helped me find a solution (see my comment on his answer).
This works:

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);
}


来源:https://stackoverflow.com/questions/23524190/how-do-i-dynamically-add-a-stylesheet-using-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!