使用自定义元素和模板访问实际/可视 DOM

问题描述 投票:0回答:1

假设我有一个叫做“面板”的东西。它包含一个隐藏部分和一个显示它的按钮。够简单的。

但是我有点喜欢,决定使用自定义元素

<custom-panel>
来标记每个面板的边界,
<template>
表示内容,
<slots>
表示配置(标题、详细信息等)。

现在我对如何连接按钮有点困惑。该模板具有 CSS,如果设置了正确的类,它将显示/隐藏面板的详细信息。但我该如何设置呢?我只知道如何获取模板的内容(没有已解析的插槽)或自定义面板的内容(没有模板信息)。

完整示例

customElements.define(
  'custom-panel',
  class extends HTMLElement {
    constructor() {
      super();

      const template = document.getElementById('custom-panel-template');
      const templateContent = template.content;

      this.attachShadow({
        mode: 'open'
      }).appendChild(
        templateContent.cloneNode(true)
      );
    }
  }
);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Custom Panels</title>
</head>

<body>

  <custom-panel>
    <span slot="openButtonText">Open Panel 1</span>
    <span slot="closeButtonText">Close Panel 1</span>
    <span slot="panelName">Panel 1</span>
    <div slot="">Panel 1 Details</div>
  </custom-panel>
  <custom-panel>
    <span slot="openButtonText">Open Panel 2</span>
    <span slot="closeButtonText">Close Panel 2</span>
    <span slot="panelName">Panel 2</span>
    <div slot="panelContent">Panel 2 Details</div>
  </custom-panel>

  <template id="custom-panel-template">
        <style type="text/css">
            #panel {
                display: none;
            }
            
            #panel.open {
                display: revert;
            }
        </style>
        
        <!-- how do these get hooked in? -->
        <button type="button"><slot name="openButtonText">Default Open Button Text</slot></button>
        <button type="button"><slot name="closeButtonText">Default Close Button Text</slot></button>
        
        <fieldset id="panel">
            <legend><slot name="panelName">Default Panel Name</slot></legend>
            <slot name="panelContent">Default Panel Content</slot>
        </fieldset>
    </template>

</body>

</html>

javascript html dom custom-element
1个回答
0
投票

customElements.define(
  'custom-panel',
  class extends HTMLElement {
    constructor() {
      super();

      const template = document.getElementById('custom-panel-template');
      const templateContent = template.content;

      this.attachShadow({
        mode: 'open'
      }).appendChild(
        templateContent.cloneNode(true)
      );

      // get a reference to the panel
      const panel = this.shadowRoot.querySelector("#panel");

      // hookup the open
      this.shadowRoot.querySelector("button#open").addEventListener("click", () => {
        panel.className = "open";
      });


      // hookup the close
      this.shadowRoot.querySelector("button#close").addEventListener("click", () => {
        panel.className = "";
      });
    }
  }
);

© www.soinside.com 2019 - 2024. All rights reserved.