html5创建自定义标签,在html中创建自定义标签

创建并使用自定义标签

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

1. 创建自定义标签

class PopUpInfo extends HTMLElement {

constructor () {

super();

// 在此定义自定义标签 我顶一个icon和text并列的

// Create a shadow root

let shadow = this.attachShadow({mode: 'open'});

// 创建我们需要的标签

let wrapper = document.createElement('div');

let iconBox = document.createElement('div');

let textBox = document.createElement('div');

// 为标签添加样式

wrapper.setAttribute('class','wapper');

iconBox.setAttribute('class','icon');

textBox.setAttribute('class','text');

let text = this.getAttribute('text'); // 获取标签里面传递的值

textBox.textContent = text;

let imgUrl;

if(this.hasAttribute('img')) {

imgUrl = this.getAttribute('img');

} else {

imgUrl = 'default.png'; // 设置一个默认图片

}

var img = document.createElement('img');

img.src = imgUrl;

iconBox.appendChild(img);

// 书写样式

var style = document.createElement('style');

let lStyleStr = '.wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 50px;}'

lStyleStr += '.icon {margin-right: 10px; width: 50px; height: 50px;}'

lStyleStr += '.icon img { width: 100%; height: 100%;}'

lStyleStr += '.text { flex: 1; font-size: 14px; color: #333; line-height: 50px;}'

style.textContent = lStyleStr;

// 将样式和dom元素挂载到页面

shadow.appendChild(style);

shadow.appendChild(wrapper);

wrapper.appendChild(icon);

wrapper.appendChild(info);

}

}

2. 注册自定义标签

customElements.define('popup-info', PopUpInfo);

3. 使用自定义标签

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值