dom基础4 — 实现一个shadow dom

<body>
    <figure-info src="https://qidian.qpic.cn/qidian_common/349573/ee4ff8502c09c020ce5e90d6a41b4c32/0" text="杨帆dom基础26"></figure>
</body>
<script type="text/javascript">
    "use strict";
    var console = window.console; 


// Create a class for the element
class FigureInfo extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a shadow root
    const shadow = this.attachShadow({mode: 'open'});

    // Create div 
    const div = document.createElement('div');
    div.setAttribute('class', 'figure');

    // Create p 
    const p = document.createElement('p');
    p.textContent = this.getAttribute('text');

    // Create img
    const img = document.createElement('img');
    img.src = this.getAttribute('src');

    // Create some CSS to apply to the shadow dom
    const style = document.createElement('style');

    style.textContent = `
      .figure {
        position: relative;
        width: 400px;
        height: 200px;
      }
      .figure img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .figure p {
        font-size: 20px;
        color: #FFF;
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        line-height: 60px;
        background-color: #000;
        text-align: center;
        margin: 0;
      }
    `;

    // Attach the created elements to the shadow dom
    shadow.appendChild(style);
    shadow.appendChild(div);
    div.appendChild(img);
    div.appendChild(p);
  }
}

// Define the new element
customElements.define('figure-info', FigureInfo);
</script>
</body>

 

posted @ 2019-03-24 18:54  PopeyeSailorMan  阅读(204)  评论(0编辑  收藏  举报