如何向阴影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-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
复制相似问题