<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 创建自定义标签 -->
<script>
class PopUpInfo extends HTMLElement {
get text() {
// debugger;
return this.getAttribute("text");
}
set text(val) {
// debugger;
this.setAttribute("text");
}
constructor() {
console.log(arguments);
super();
console.log(this);
// 在此定义自定义标签 我顶一个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", "wrapper");
iconBox.setAttribute("class", "icon");
textBox.setAttribute("class", "text");
// debugger;
// 获取标签里面传递的值
// let text = this.getAttribute("text");
let text = this.text;
textBox.textContent = text;
let imgUrl;
if (this.hasAttribute("img")) {
imgUrl = this.getAttribute("img");
}
else {
imgUrl = "https://note.youdao.com/web/images/dummy_user-85ee808751.jpg"; // 设置一个默认图片
}
var img = document.createElement("img");
img.src = imgUrl;
iconBox.appendChild(img);
// 书写样式
let style = document.createElement("style");
let lStyleStr = `.wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 50px;}
.icon { margin-right: 10px; width: 50px; height: 50px;}
.icon img { width: 100%; height: 100%;}
.text { flex: 1; font-size: 14px; color: #333; line-height: 50px;}`;
style.textContent = lStyleStr;
// 将样式和dom元素挂载到页面
shadow.appendChild(style);
shadow.appendChild(wrapper);
wrapper.appendChild(iconBox);
wrapper.appendChild(textBox);
}
}
</script>
<!-- 使用自定义标签 -->
<popup-info img="https://himg.bdimg.com/sys/portraitn/item/8f9f77616e6779696875323030390e09" text="你的文字">
</popup-info>
<!-- 注册自定义标签 -->
<script>
window.customElements.define('popup-info', PopUpInfo);
</script>
</body>
</html>
<!-- https://www.cnblogs.com/tmbm/p/11115871.html -->
网友评论