在html中创建自定义标签

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

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('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);
	}
}
</script>


2. 注册自定义标签

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


3. 使用自定义标签

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


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_3980