Luk*_*kas 3 javascript shadow-dom html5-template
假设我创建并插入了一个这样的元素
<template id="react-web-component">
<span>template stuff</span
<script src="/static/js/bundle.js" type="text/javascript"></script>
</template>
<script>
(function (window, document) {
const doc = (document._currentScript || document.currentScript).ownerDocument;
const proto = Object.create(HTMLElement.prototype, {
attachedCallback: {
value: function () {
const template = doc.querySelector('template#react-web-component').content;
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.cloneNode(true));
},
},
});
document.registerElement('react-web-component', { prototype: proto });
})(window, document);
</script>
<react-web-component></react-web-component>
Run Code Online (Sandbox Code Playgroud)
现在我想使用 aquerySelector来访问我的元素的开放阴影 dom。像这样:
document.querySelector('react-web-component::shadow')
Run Code Online (Sandbox Code Playgroud)
但这不起作用。有没有其他办法?
编辑以回应@Supersharp 的回答
对不起,我没有说清楚。我使用的 webpack
style-loader只接受一个 CSS 选择器,它与 一起使用document.querySelector,所以我要的是一个我可以用这种方式使用的 CSS 选择器。
通过shadowRootShadow主机的属性获取:
document.querySelector('react-web-component').shadowRoot
Run Code Online (Sandbox Code Playgroud)
更新
曾经有这种 CSS 选择器,但现在已弃用。
也许您可以尝试使用普通 DOM 而不是 Shadow DOM。
| 归档时间: |
|
| 查看次数: |
2982 次 |
| 最近记录: |