Pregunta

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

¿Fue útil?

Solución 2

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

Otros consejos

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

For anyone who needs to add an external stylesheet, this is how you do it.

LinkElement link = document.head.append(LinkElement());
link.type = "text/css";
link.rel = "stylesheet";
link.href = "/site.css";
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top