【发布时间】:2017-05-30 09:15:44
【问题描述】:
如何为 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>
导航组件.html
<template>
<style>
.btn {
background-color: green;
padding: 10px 20px;
}
</style>
<button onclick="getstyles()">ENTER</button>
</template>
<script src="nav-component.js"></script>
导航组件.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 类添加到 button 元素 ,以便将其样式添加到 button 元素中
出错了 未捕获的类型错误:无法读取 null 的属性“classList”
【问题讨论】:
-
你不能不用Jquery吗? $('#buttonId').addClass('btnClass')
-
仅供参考,
document.registerElement已弃用:developer.mozilla.org/de/docs/Web/API/Document/registerElement
标签: javascript web-component shadow-dom custom-element