[英]How can I select elements in shadow dom through the parent element based on the click event on addEventListener?
I have a web component, like this:我有一个 web 组件,如下所示:
File: download-bar.js (web component)文件:download-bar.js(网络组件)
class DownloadBar extends HTMLElement {
constructor() {
super();
this.shadowDOM = this.attachShadow({mode: 'open'});
}
connectedCallback() {
this.render();
}
render() {
this.shadowDOM.innerHTML = `
<div class="favicon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="black" width="18px" height="18px"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg>
<span>Download File</span>
</div>
<div class="dropdown">
<a href="" id="xlsx">XLSX</a>
<a href="" id="pdf">PDF</a>
<a href="" id="jpeg">JPEG</a>
</div>
`;
}
}
customElements.define('download-bar', DownloadBar);
and I do a selection of elements on the parent shadow element DOM and listen to the click event, like this:我在父阴影元素 DOM 上选择元素并监听 click 事件,如下所示:
File: download-bar.js文件:下载-bar.js
import '../component/download-bar.js';
const downloadElement = document.querySelector('download-bar');
downloadElement.addEventListener('click', (e) => {
// I would like this:
if (e.target.classList.contains('favicon')) {
console.log('True')
}
})
how can I get child elements from custom elements using shadow dom, if an event from "(e)" that is obtained has a certain class or id, for example class = "favicon"?如果从“(e)”获得的事件具有特定的 class 或 id,例如 class =“favicon”,我如何使用 shadow dom 从自定义元素中获取子元素?
You need to use event.composedPath()
您需要使用
event.composedPath()
If you use Custom Events be sure to set the composed:true
option so your event breaks out of shadowDom如果您使用自定义事件,请务必设置compose
composed:true
选项,以便您的事件脱离shadowDom
You can replace all this:您可以替换所有这些:
constructor() {
super();
this.shadowDOM = this.attachShadow({mode: 'open'});
}
connectedCallback() {
this.render();
}
render() {
this.shadowDOM.innerHTML = ...
with:和:
connectedCallback() {
this.attachShadow({mode: 'open'}).innerHTML = ...
}
You aren't doing anything special in the constructor
;您在
constructor
中没有做任何特别的事情; so don't define it and let the element run the constructor
from HTMLElement.所以不要定义它,让元素从 HTMLElement 运行
constructor
。
attachShadow()
both sets and returns this.shadowRoot
attachShadow()
设置并返回this.shadowRoot
Only when you move/append/drag around Custom Elements in the DOM will the connectedCallback
run again, and you might want to split creating shadowDOM to its own constructor
只有当您在 DOM 中移动/附加/拖动自定义元素时,
connectedCallback
才会再次运行,并且您可能希望将创建 shadowDOM 拆分为它自己的constructor
Also see: https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/另请参阅: https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.