首页 > 解决方案 > 访问 shadow dom 属性

问题描述

所以这是我的脚本代码

class Pop extends HTMLElement {
  constructor() {
    super();
  }
 connectedCallback() {
 let currDoc = document.currentScript.ownerDocument;
  let template = currDoc.querySelector('#pop-up');
  let tmplNode = document.importNode(template.content, true);

  let shadowRoot = this.createShadowRoot();
  shadowRoot.appendChild(tmplNode);
  shadowRoot.querySelector("#content").innerHTML = this.innerHTML;
 }
}
 window.customElements.define("pop-up", Pop);

这是我的模板

<template id="pop-up">
    <style>
     * {
     padding: 0;
      margin: 0;
    }

.btn {
  //styling
}

.btn:hover {
  //styling
}

#box{
    //styling
    display: none;
}

#box h1{
    //styling
}

 </style>

<div id="box">
    <h1> Your Shopping Cart</h1>
    <text id="content"> </text>

    <button class="btn" onclick="close()"> Close </button>
</div>
</template>

在我的索引文件中我有这个

<button class="btn" onclick="pop()">Show Pop</button>
<pop-up id="pop"> pop-up box</pop-up>

<script>
    function pop(){
        document.getElementById("pop").style.display = "block";
    }
</script>

我正在尝试做一个弹出框。当我单击“显示弹出”按钮时,我想将显示属性从样式更改为从“无”到“块”。但由于某种原因,它不起作用。我是这个影子 dom 元素的新手,我真的想不通。

标签: javascriptdomshadow

解决方案


很难解释此答案中的所有内容,但以下代码将为您概述解决方案的外观。

像往常一样,MDN在这里对 Web 组件和影子 dom 进行了完美的介绍

 class Pop extends HTMLElement {
      constructor() {

        // Always call super first in constructor
        super();
        let template = document.getElementById('pop-up');
        let templateContent = template.content;

        // Create a shadow root
        const shadowRoot = this.attachShadow({ mode: 'open' })
          .appendChild(templateContent.cloneNode(true));
         
        // attach close listener
        this.shadowRoot.querySelector('.btn').addEventListener('click', this.close.bind(this));
      }
     
      //  close pop-up
      close() {
        this.style.display = 'none';
      }

      //  open pop-up
      open() {
        this.style.display = 'block';
      }
    }
    window.customElements.define("pop-up", Pop);
    
     function pop() {
      // notice we are using the open method here 
      document.getElementById("pop").open();
    }
  <template id="pop-up">
    <style>
      :host {
        display: none;
      }

      * {
        padding: 0;
        margin: 0;
      }

      .btn {
        //styling
      }

      .btn:hover {
        //styling
      }

      #box {
        //styling
        display: none;
      }

      #box h1 {
        //styling
      }
    </style>

    <div id="box">
      <h1> Your Shopping Cart</h1>
      <!-- Notice we are using slots -->
      <slot> </slot>

      <button class="btn"> Close </button>
    </div>
  </template>
  
   <button class="btn" onclick="pop()">Show Pop</button>
  <pop-up id="pop"> pop-up box </pop-up>


推荐阅读