首页 > 其他 > 详细

dom基础4 — 实现一个shadow dom

时间:2019-03-24 19:44:32      阅读:124      评论:0      收藏:0      [点我收藏+]
<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>

 

dom基础4 — 实现一个shadow dom

原文:https://www.cnblogs.com/popeyesailorman/p/10589529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!