如何向阴影DOM添加动态样式
index.html
<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
    <link rel="import" href="nav-component.html">
</head>
<body>
    <app-nav></app-nav>
</body>
</html>nav-component.html
<template>
  <style>
    .btn {
        background-color: green;
        padding: 10px 20px;
    }
  </style>
    <button onclick="getstyles()">ENTER</button>
</template>
<script src="nav-component.js"></script>nav-component.js
let template = document.currentScript.ownerDocument.querySelector('template');
let clone = document.importNode(template.content, true);
let proto = Object.create(HTMLElement.prototype);
proto.createdCallback = function () {
    let root = this.createShadowRoot();
    root.appendChild(clone);
}
document.registerElement('app-nav', {
    prototype: proto
});
function getstyles() {
    console.log('it works');
    document.querySelector('button').classList.add('btn');
    // document.currentScript.ownerDocument.querySelector('button').classList.add('btn');
}必须将btn类添加到按钮元素,以便将其样式添加到按钮元素中。
got错误Uncaught :无法读取空的属性“classList”
演示
发布于 2017-05-30 10:29:49
首先,不推荐document.registerElement,所以我在这里回答了基于类的自定义元素解决方案.
解决方案是从document.currentScript.ownerDocument获取文档
class AppNavElement extends HTMLElement {
    constructor() {
        super()
        // import from ownerDocument
        const importDoc = document.currentScript.ownerDocument;
        let shadowRoot = this.attachShadow({mode: 'open'});
        const template = importDoc.querySelector('#template');
        const instance = template.content.cloneNode(true);
        shadowRoot.appendChild(instance);
        // Event Listener
        this.addEventListener('click', e => this.changeStyle());
    }
    changeStyle() {
        this.shadowRoot.querySelector('button').classList.add('btn')
    }
}
customElements.define('app-nav', AppNavElement)更新:
要侦听按钮元素,只需使用connectedCallback谢@bhv
connectedCallback() { 
    let btn = this.shadowRoot.querySelector('button') 
    // Event Listener 
    btn.addEventListener('click', e => this.changeStyle()); 
}发布于 2017-05-31 20:58:43
您还可以简单地从<button>属性获取event.target元素:
function changeStyle() {
    console.log('it works');
    event.target.classList.add('btn');
}
...
<button onclick="changeStyle()">ENTER</button>https://stackoverflow.com/questions/44258159
复制相似问题