2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

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的方式引入

图片名称

posted on   qize  阅读(729)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

导航

0 commits in this month

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示