簡體   English   中英

如何基於addEventListener上的點擊事件通過父元素在shadow dom中select元素?

[英]How can I select elements in shadow dom through the parent element based on the click event on addEventListener?

我有一個 web 組件,如下所示:

文件: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);

我在父陰影元素 DOM 上選擇元素並監聽 click 事件,如下所示:

文件:下載-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')
    }
})

如果從“(e)”獲得的事件具有特定的 class 或 id,例如 class =“favicon”,我如何使用 shadow dom 從自定義元素中獲取子元素?

您需要使用event.composedPath()

如果您使用自定義事件,請務必設置compose composed:true選項,以便您的事件脫離shadowDom

順便提一句

您可以替換所有這些:

    constructor() {
        super();
        this.shadowDOM = this.attachShadow({mode: 'open'});        
    }

    connectedCallback() {
        this.render();
    }

    render() {
        this.shadowDOM.innerHTML = ...

和:

    connectedCallback() {
        this.attachShadow({mode: 'open'}).innerHTML = ...
    }

您在constructor中沒有做任何特別的事情; 所以不要定義它,讓元素從 HTMLElement 運行constructor

attachShadow()設置並返回this.shadowRoot

只有當您在 DOM 中移動/附加/拖動自定義元素時, connectedCallback才會再次運行,並且您可能希望將創建 shadowDOM 拆分為它自己的constructor


另請參閱: https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM