Web Components实现自定义元素

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<template id="userCardTemplate">
		<style>
			.box{
     
     
				background: gray;
				color: #fff;
				display: flex;
				width: 400px;
				box-sizing: border-box;
				padding: 10px;
			}
			.image{
     
     
				width: 100px;
				height: 100px;
				margin-right: 20px;
			}
		</style>
		
		<div class="box">
			<img class="image">
	  	<div class="container">
		    <p class="name"></p>
		    <p class="email"></p>
  		</div>
		</div>		
	</template>

	<test-card 
	image="https://semantic-ui.com/images/avatar2/large/kristy.png"
  name="User Name"
  email="[email protected]"></test-card>

	<script>
		class TestCard extends HTMLElement {
     
     
		  constructor() {
     
     
		    super();
		    const templateElem = document.getElementById('userCardTemplate');
		    const content = templateElem.content.cloneNode(true);
		    content.querySelector('img').setAttribute('src', this.getAttribute('image'));
		    content.querySelector('.container>.name').innerText = this.getAttribute('name');
		    content.querySelector('.container>.email').innerText = this.getAttribute('email');
		    this.appendChild(content);
		  }
		}  
		window.customElements.define('test-card',TestCard);
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_35958891/article/details/107164435