如何向shadow 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 类添加到按钮元素,以便将其样式添加到按钮元素
得到了错误 未捕获的TypeError:无法读取null的属性'classList'
答案 0 :(得分:3)
首先,{@ 1}}已弃用,所以我在这里回答了基于类的自定义元素解决方案......
解决方案是从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)
感谢@bhv
connectedCallback
答案 1 :(得分:1)
您也可以从<button>
属性中获取event.target
元素:
function changeStyle() {
console.log('it works');
event.target.classList.add('btn');
}
...
<button onclick="changeStyle()">ENTER</button>