zoukankan      html  css  js  c++  java
  • Web Components

    Web Components是什么


    Web Components是一个聚集html,css,js的一个可复用组件。
    这样开发者就可以在网络上通过插件或组件的形式分享自己的代码片段(具有独立的功能),也可以理解成web组件或插件。

    Web Components的组成要素


    • 自定义元素
    • html模版
    • shadowDOM
    • HTML(组件)导入

    shadowDOM是什么


    定义:浏览器将模板、样式表、属性、JavaScript代码等,封装成一个独立的DOM元素。外部的设置无法影响到其内部,而内部的设置也不会影响到外部,与浏览器处理原生网页元素(比如<video>元素)的方式很像

    <!DOCTYPE html>
    <html>
      <head>
         <title>Shadow DOM</title>
      
         <style>
           button {
              font: 18px Century Schoolbook;
              border: thin solid gray;
              background: rgba(200, 200, 200, 0.5);
              padding: 10px;
           }
         </style>
      </head>
      
      <body>
           
        <div class="container"></div>
     
        <script>
          var host = document.querySelector('.container');
          var root = host.createShadowRoot();
          root.innerHTML = '<p>How <em>you</em> doin?</p>'
        </script>
      </body>
    </html>
    
    图片名称

    独立的组件


    组件有两种形式

    • 非shadowDOM组件
    • shadowDOM组件

    非shadowDOM组件

    temp.html

    <script>
      var proto = Object.create(HTMLElement.prototype);
     
      proto.createdCallback = function() {
        var name = this.getAttribute('name');
        this.innerHTML = '欢迎来到web组件, <b>' +
                         (name || '?') + '</b>';
      };
     
      document.registerElement('say-hi', {prototype: proto});
    </script>
    

    shadowDOM组件

    temp2.html

    <template id="t">
      <style>
        ::content > * {
          color: red;
        }
      </style>
      <span>I'm a shadow-element using Shadow DOM!</span>
      <content></content>
    </template>
     
    <script>
      (function() {
        // 指向被加载的网页
        var importDoc = document.currentScript.ownerDocument;
     
        // 定义并登记<shadow-element>
        var proto2 = Object.create(HTMLElement.prototype);
     
        proto2.createdCallback = function() {
          var template = importDoc.querySelector('#t');
          var clone = document.importNode(template.content, true);
          var root = this.createShadowRoot();
          root.appendChild(clone);
        };
     
        document.registerElement('shadow-element', {prototype: proto2});
      })();
    </script>
    

    知识点

    • HTMLElement.prototype:为自定义注册的元素指定原型
    • createdCallback:是实例生成时触发的hook
    • registerElement:注册自定义组件

    组件引入


    shadow.html

    <link rel="import" href="temp.html"/>
    <link rel="import" href="temp1.html"/>
    

    直接通过link的方式引入

    图片名称
  • 相关阅读:
    (转)回车 执行button点击
    (转)sp_executesql介绍和使用
    (转)SQL Server 2008将数据导出为脚本 [SQL Server]
    (转)Phonegap VS AppCan
    (转)asp.net动态设置标题title 关键字keywords 描述descrtptions
    Ubuntu Tomcat Service
    Ubuntu使用ssh方法连接不上
    Ubuntu输入su提示认证失败的解决方法
    Redis通过命令行进行配置
    linux下安装redis3.2
  • 原文地址:https://www.cnblogs.com/zqzjs/p/7360664.html
Copyright © 2011-2022 走看看