企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一、概述 htc的全称就是Html Components,由微软在IE5.0后开始提供的一种新的指令组合,它可以把某种特定功能的代码封装在一个组件之中,从而实现了代码的重复使用,据说是用来代替activex和applet的;它可以以两种方式被引入到HTML页面中,一种是作为“行为”被附加到元素,使用CSS引入,一种是作为“组件”,扩展HTML的标签体系。 Html Components虽然规范很早就指定出来,但现在基本没落了,不再被主流浏览器支持; 后续出现类似的技术,Web Components ,它包括以下四种技术(每种都可以被单独使用); HTML 组件是封装的对象,也像 ActiveX 控件一样是“自包含”的,可以在开发完后发布给任何人。HTC 文件并不仅仅是将一个 HTML 文件的扩展名换成 .htc,它含有脚本和 HTC 定制元素的集合。 Chrome完全支持Html Components规范; ## 二、说明 Web Components 包括以下四种技术(每种都可以被单独使用): Shadow DOM 一种可以在document下组合多个同级别并且可以项目作用的DOM树的方法,因此可以更好完善DOM的构成 Custom Elements 一种可以允许开发者在document中定义并使用的新的dom元素类型,即自定义元素 ; HTML Templates 模板没什么可说了,在标准实现之前其实我们一直都在用js来实现该方式 HTML Imports 一种允许一个html文档在别的htmldocuments中包含和复用的方法 ## 三、实例 index.html ``` <!DOCTYPE> <html> <head> <title>webcomponent</title> <link rel="import" href="./components/helloword.html" /> </head> <body> <hellow-world></hellow-world> </body> </html> ``` ``` <template> <style> .coloured { color: red; } </style> <p>the first webcompnent is <strong class="coloured">Hello World</strong></p> </template> <script> (function() { // Creates an object based in the HTML Element prototype // 基于HTML Element prototype 创建obj var element = Object.create(HTMLElement.prototype); // 获取特mplate的内容 var template = document.currentScript.ownerDocument.querySelector('template').content; // element创建完成之后的回调 element.createdCallback = function() { // 创建 shadow root var shadowRoot = this.createShadowRoot(); // 向root中加入模板 var clone = document.importNode(template, true); shadowRoot.appendChild(clone); }; document.registerElement('hellow-world', { prototype: element }); }()); </script> ``` ![](https://img.kancloud.cn/bb/67/bb67d6af8b3c12d7f6d44f8f55b156d9_836x352.png)