【发布时间】:2022-01-26 04:06:06
【问题描述】:
我一直在尝试通过扩展 HTMLElement 类来制作自定义 HTML 元素。我尝试通过链接与我的其他两个文件位于同一目录中的 CSS 文件来添加一些样式 - index.html 和 custom.css。
主文件夹
- index.html
- custom.css
- custom.js
index.html:
<!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>
<link rel="nofollow" type="text/css" href=''>
</head>
<body>
<script src="./custom.js"></script>
<smooth-button text="Smooth button" no-1 = 1 no-2 = 2></smooth-button>
</body>
</html>
custom.css:
smooth-button{
display: block;
color: blue;
background-color: orange;
}
custom.js:
class SmoothButton extends HTMLElement{
constructor(){
super();
this.shadow = this.attachShadow({mode: "open"})
}
connectedCallback(){
this.render();
}
render(){
this.SumOfNo1AndNo2 = null;
if(this.getAttribute("no-1")!=null && this.getAttribute("no-2")!=null){
this.SumOfNo1AndNo2 = parseInt(this.getAttribute("no-1")) +
parseInt(this.getAttribute("no-2"));
}
else{
console.log("Invalid attribute.")
}
this.shadow.innerHTML = `<button>` + this.getAttribute("text") + " " + this.SumOfNo1AndNo2
+ "</button>"
}
}
customElements.define("smooth-button", SmoothButton);
这样,我按预期得到了一个带有文本的按钮,但样式应用于整个元素,而不是构成它的元素。如何使用外部 CSS 文件将样式分别应用于其每个元素(现在只是 <button>)?我正在使用外部 CSS,因为我阅读它时感觉更好here。
【问题讨论】:
-
不管怎样,你有一些无效的 HTML。确保引用您的属性值
no-1和no-2。
标签: javascript html css shadow-dom custom-element