这可能有点令人困惑。我正在尝试从我的自定义元素访问innerHTML 或childNodes。是否可以从Web组件导入文件访问原始DOM结构?在 AttachShadow 之前?
在下面的示例中,我尝试从 jookah-gallery 导入文件访问两个 jookah-images 的 src。
免责声明:当涉及到 Shadow DOM 和 Web 组件时,我完全是个菜鸟,所以如果有任何重大错误,我很想了解原因。谢谢你的帮助!
索引.html
<jookah-gallery>
//here
<jookah-image class="gallery-image" src="http://merehead.com/blog/wp-content/uploads/gradient-design.jpeg">
<jookah-image class="gallery-image" src="https://webgradients.com/public/webgradients_png/035%20Itmeo%20Branding.png">
</jookah-gallery>
jookah-gallery 的导入文件:
(function(owner) {
class jookahGallery extends HTMLElement {
constructor() {
super();
//this returns false
if (this.hasChildNodes()) {
console.log('there are nodes')
}else{
console.log('NO nodes')
}
//shadow DOM attach
const shadowRoot = this.attachShadow({mode: 'open'});
const template = owner.querySelector('#jookah-gallery-template');
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
// ---------------- object events -------------------------//
connectedCallback() {
}
render(){
}
disconnectedCallback(){
}
attributeChangedCallback(){
}
// ---------------- methods ------------------------//
}
customElements.define('jookah-gallery', jookahGallery);
})(document.currentScript.ownerDocument);
根据规范,您不应该在 Web 组件的构造函数中检查、更改、添加子项。
https://w3c.github.io/webcomponents/spec/custom/#custom-element-conformance https://w3c.github.io/webcomponents/spec/custom/#custom-element-conformance
相反,您需要将孩子们的阅读移至连接的回调中:
class jookahGallery extends HTMLElement {
constructor() {
super();
this._childrenRead = false;
const shadowRoot = this.attachShadow({mode: 'open'});
const template = document.createElement('template');
template.innerHtml = `Place your template here`;
const instance = template.content.cloneNode(true);
shadowRoot.appendChild(instance);
}
connectedCallback() {
if (!this._childrenRead) {
this._childrenRead = true;
if (this.hasChildNodes()) {
console.log('there are nodes')
}else{
console.log('NO nodes')
}
}
}
}
customElements.define('jookah-gallery', jookahGallery);
您还可以使用<slot> https://developers.google.com/web/fundamentals/web-components/shadowdom#slots嵌入您的孩子。但是有一些CSS问题你需要解决意识到 https://developers.google.com/web/fundamentals/web-components/shadowdom#stylefromoutside使用插槽时。
请记住,shadowDOM 并非在所有浏览器中都受支持,并且不是一个简单的填充。因此,如果您只使用 Chrome 和 Safari,那就去吧。如果您计划支持更广泛的浏览器,那么您可能还不想使用 ShadowDOM。
https://alligator.io/web-components/composition-slots-named-slots/ https://alligator.io/web-components/composing-slots-named-slots/
还可以在这里阅读更多内容:如何在 Web 组件中使用子元素 https://stackoverflow.com/questions/49027807/how-to-use-child-elements-in-web-components
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)