创建并使用自定义标签

Web Components 标准非常重要的一个特性是,它使开发者能够将HTML页面的功能封装为 custom elements(自定义标签),本篇介绍使用 CustomElementRegistry 来管理我们的自定义标签

1. 创建自定义标签

  <script>
class PopUpInfo extends HTMLElement {
constructor () {
super();
// 在此定义自定义标签 我顶一个icon和text并列的
// Create a shadow root
let shadow = this.attachShadow({mode: 'open'});
  // 创建我们需要的标签
let wrapper = document.createElement(&#39;div&#39;);
let iconBox = document.createElement(&#39;div&#39;);
let textBox = document.createElement(&#39;div&#39;); // 为标签添加样式
wrapper.setAttribute(&#39;class&#39;,&#39;wapper&#39;);
iconBox.setAttribute(&#39;class&#39;,&#39;icon&#39;);
textBox.setAttribute(&#39;class&#39;,&#39;text&#39;); let text = this.getAttribute(&#39;text&#39;); // 获取标签里面传递的值
textBox.textContent = text; let imgUrl;
if(this.hasAttribute(&#39;img&#39;)) {
imgUrl = this.getAttribute(&#39;img&#39;);
} else {
imgUrl = &#39;default.png&#39;; // 设置一个默认图片
}
var img = document.createElement(&#39;img&#39;);
img.src = imgUrl;
iconBox.appendChild(img); // 书写样式
var style = document.createElement(&#39;style&#39;);
let lStyleStr = &#39;.wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 50px;}&#39;
lStyleStr += &#39;.icon {margin-right: 10px; width: 50px; height: 50px;}&#39;
lStyleStr += &#39;.icon img { width: 100%; height: 100%;}&#39;
lStyleStr += &#39;.text { flex: 1; font-size: 14px; color: #333; line-height: 50px;}&#39;
style.textContent = lStyleStr; // 将样式和dom元素挂载到页面
shadow.appendChild(style);
shadow.appendChild(wrapper);
wrapper.appendChild(icon);
wrapper.appendChild(info); }

}
</script>

2. 注册自定义标签

  <script>
customElements.define('popup-info', PopUpInfo);
</script>

3. 使用自定义标签

<body>
<popup-info img="you_picture.jpg" text="你的文字"></popup-info>
</body>

最新文章

  1. Which language is best, C, C++, Python or Java?什么编程语言最好
  2. BZOJ4539: [Hnoi2016]树
  3. easy ui插件
  4. vim 查看文件二进制格式
  5. Python全栈之路8--迭代器(iter)和生成器(yield)
  6. 前端面试题和setTimeout异步
  7. HDU 4548 美素数
  8. InstallShield Custom Dialog
  9. VOA学习-South Sudan Must Allow Aid
  10. HTML5移动开发中的input输入框类型
  11. 批处理WMIC查看补丁情况
  12. android 删除的警告对话框
  13. 高性能C++网络库libtnet实现:Connection
  14. 直接插入排序---java实现
  15. CSS简介及基本知识
  16. idea通过mapper快速定位到xml文件
  17. 使用git将项目上传到github
  18. RAMPS1.4 3d打印控制板接线与测试
  19. iOS 申请distribution证书, 公钥,私钥
  20. Redis的Sorted Set有序集合命令

热门文章

  1. MyBatis映射器(转载)
  2. 到头来还是逃不开Java - Java13面向对象基础
  3. Python编程使用PyQT制作视频播放器
  4. 2.1.1Remove Duplicates from Sorted Arr
  5. k8spod的介绍
  6. js缓慢运动,Math.ceil向上取整,floor向下取整
  7. Python学习第十三课——re(正则表达式)模块
  8. 使用mysql服务实现负载均衡
  9. HTML标签,CSS简介
  10. 树莓派4B踩坑指南 - (5)设置阿里云的源及解决apt提示依赖