• 谈谈Web Components


    一.什么是web components?

        web components是一套允许开发人员自定义元素创建可重用组件的技术

    二.怎么使用?

      1.创建一个类或函数来指定web组件功能,例如使用es6的class

      2. 通过customElements.define()方法注册自定义元素,并向其传递要定义的元素名称,指定元素功能的类,以及可选的其所继承自的元素。

      3.如果需要的话可以使用Element.attachShadow()方法将一个shadow DOM附加到自定义元素上。使用原生的DOM方法向shadow DOM中添加子元素。

     4.如果需要的话,使用<template>和<slot>定义一个HTML模板。再次使用常规DOM方法克隆模板并将其附加到shadow DOM中。

     5.最后在页面中像使用原生的HTML元素一样,使用自定义的元素

    三.实例

     

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Web Components</title>
    </head>
    <body>
        <custom-button></custom-button>
          //这是自定义的元素(像使用原生HTML元素一样使用自定义的元素)
        <template id="custom-button">//使用template定义一个HTML模板
            <button>自定义按钮</button>
              //添加样式
             <style>
                button {
                    display: inline-block;
                    line-height: 1;
                    white-space: nowrap;
                    cursor: pointer;
                    text-align: center;
                    box-sizing: border-box;
                    outline: none;
                    margin: 0;
                    transition: .1s;
                    font-weight: 500;
                    padding: 12px 20px;
                    font-size: 14px;
                    border-radius: 4px;
                    color: #fff;
                    background-color: #409eff;
                    border-color: #409eff;
                    border: 0;
                }
    
                button:active {
                    background: #3a8ee6;
                    border-color: #3a8ee6;
                    color: #fff;
                }
              </style>
        </template>
        <script>
            class CustomButton extends HTMLElement {
                  constructor() {
                     super()
                     const templateContent=document.getElementById('custom-button').content
                //获取自定义模板
                      const shadowRoot = this.attachShadow({mode:'open'})
                      shadowRoot.appendChild(templateContetn.cloneNode(true))
                      //使用attachShadow()方法将一个shadow DOM附加到自定义元素
                      shadowRoot.querySelector('button').onClick=()=>{
                       alert('hello world')
                     }
                     //绑定点击事件
                  }
             }
           customElements.define('custom-button', CustomButton)
          //注册自定义元素
         </script>
    </body>            

    四.运行结果

  • 相关阅读:
    仿QQ信息弹出
    天高云淡 leobbs皮肤
    http://www.xywq.com/files/ganzhi11.htm
    用Silverlight打造位运算器(3)--完成
    用Silverlight打造位运算器(1)--制作简易工具条控件
    用Silverlight打造位运算器(2)--制作数字文本框控件
    Lucky Sequence[SRM403DIVI500]
    答复:“判断一个整数的二进制位中有多少个1”的提问
    Python 笔记(1)
    #define中的#、## && #@
  • 原文地址:https://www.cnblogs.com/myspecialzone/p/14372764.html
Copyright © 2020-2023  润新知