使用聚合物元素中的模板中的dart动态更新样式表

时间:2015-05-16 22:17:05

标签: html css dom dart dart-polymer

我正在动态更新样式表,如this other SO page中所述。一般来说它很好用,但它不适用于我的聚合物元素模板中的HTML DOM标签(例如,我不能改变.above-board的样式)。

你知道我怎么能让它发挥作用?除了直接在每个元素的HTML中嵌入样式更改而不是使用类。显示以下代码(尝试删除尽可能多的不相关代码):

的index.html

<!DOCTYPE html>
<html lang="en">

    ...

    <body>
        <div class="main">
            <panepond-board class="player1"></panepond-board>
        </div>
        <script type="application/dart" src="board.dart"></script>
    </body>
</html>

component.html

<link rel="import" href="packages/polymer/polymer.html"/>
<polymer-element name="panepond-board">
    <template>
        <div class="above-board">
            <input type="button" value="toggle config" on-click="{{toggleConfig}}" class="update"/><br/>
            <label>score: {{totalScore}}</label>
        </div>

        ...

        <link rel="stylesheet" href="board.css"/>
    </template>
</polymer-element>
<script type="application/dart" src="board.dart"></script>

board.dart

import 'dart:html';
import 'dart:async';
import 'dart:math';
import 'package:polymer/polymer.dart';
import "package:range/range.dart";
import 'config.dart';

main() {
    initPolymer().run(() {
        Polymer.onReady.then((_) {
            var board1 = querySelector('.player1');
            window.onKeyDown.listen( (e) {
                board1.actOnKeyDown(new String.fromCharCodes([e.keyCode]));
            });
            board1.init();
        });
    });
}


@CustomTag('panepond-board')
class Board extends PolymerElement {
    @observable Config config = new Config(6);
    Board.created() : super.created();

    void init() {
        config.loadCSS();
    }

config.dart

import 'package:polymer/polymer.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:html';

class Config extends Observable {
        num width;
        Config(w) : width = w;

        void loadCSS() {
            StyleElement styleElement = new StyleElement();
            document.head.append(styleElement);
            CssStyleSheet sheet = styleElement.sheet;
            final rule1 = '.above-board { border: 1px solid blue; }';
            sheet.insertRule(rule1, sheet.cssRules.length); //this doesn't show any effect
            final rule2 = '.main { border: 1px solid red; }';
            sheet.insertRule(rule2, sheet.cssRules.length); //this works fine
        }
}

如果我在.above-board{border: 1px solid blue;}上手动附加board.css,规则将按预期工作(即它将显示蓝色边框)。否则,以编程方式执行此操作(请参阅上面的rule1)无效。

1 个答案:

答案 0 :(得分:1)

我认为

document.head.append(styleElement);

应该是

document.querySelector('panepond-board.player1')
    .shadowRoot.append(styleElement);