900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > html5创建自定义标签 在html中创建自定义标签

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

时间:2024-04-09 10:37:57

相关推荐

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. 使用自定义标签

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。