Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

dom - How do I dynamically add a stylesheet using Dart?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...