使用 classList 在 JavaScript 的 Web 组件中动态添加 class

add class dynamically in web components from JavaScript using classList

如何给阴影添加动态样式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>

导航-component.html

<template>
  <style>
    .btn {
        background-color: green;
        padding: 10px 20px;
    }
  </style>
    <button onclick="getstyles()">ENTER</button>
</template>
<script src="nav-component.js"></script>

导航-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 class 添加到 button element ,以便其样式添加到 button element

遇到错误 未捕获类型错误:无法读取 属性 'classList' of null

Demo

首先 document.registerElement 已被弃用,所以我在这里回答了基于 class 的自定义元素解决方案...

解决方案是从 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()); 
}

您也可以简单地从 event.target 属性 中获取 <button> 元素:

function changeStyle() {
    console.log('it works');
    event.target.classList.add('btn');
}

...

<button onclick="changeStyle()">ENTER</button>