javascript - 扩展 HTMLButtonElement 的 WebComponent 没有调用 constructor() 和 connectedCallBack()
问题描述
我正在尝试创建一个Web 组件 button
,但是当我在 HTML 中添加它时,该constructor()
函数永远不会被调用。
class MyButton extends HTMLButtonElement {
title = "";
constructor({ title }) {
super();
this.title = title;
this.addEventListener("click", (e) => this.rippe(e.offsetX, e.offsetY));
}
rippe(x, y) {
let div = document.createElement("div");
div.classList.add("ripple");
this.appendChild(div);
div.style.top = `${y - div.clientHeight / 2} px`;
div.style.left = `${x - div.clientWidth / 2} px`;
div.style.backgroundColor = "currentColor";
div.classList.add("run");
div.addEventListener("transitioned", (e) => div.remove());
}
connectedCallback() {
this.innerHTML = this.title;
}
}
window.customElements.define("my-button", MyButton, { extends: "button" });
my-button {
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
background: #12c2e9;
background: -webkit-linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
background: linear-gradient(to right, #12c2e9, #c471ed, #f64f59);
border-radius: 28px;
border: none;
height: 56px;
width: 268px;
outline: none;
color: #fff;
font-size: 16px;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}
my-button:hover {
filter: contrast(90%);
}
my-button:active {
filter: contrast(85%);
}
<!DOCTYPE html>
<html lang="pt">
<head title="test page">
<script type="text/javascript" src="./my_button.js"></script>
<link rel="stylesheet" type="text/css" href="./my_button.css" />
</head>
<meta charset="UTF-8" />
<title>web components</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<body>
<my-button title="Wab components!"></my-button>
</body>
</html>
我面临一些问题:
1-constructor()
没有被调用所以我的事件监听器没有被添加到元素中;
2-connectedCallback ()
生命周期也没有被调用,所以我的按钮没有title
作为参数传递;
为什么会发生这种情况,我该如何解决?
constructor()
只有当我实例化我的自定义元素并附加到`body:
let popup = new PopUpInfo();
document.body.appendChild(popup);
但我会在 HTML 中使用我的自定义选择器“我的按钮”而不是附加它。
解决方案
回复:来自评论
该链接指向HTMLButtonElement
所有浏览器都支持的标准元素。
有 2 种不同风格的 Web 组件:
详情请参阅Web 组件:扩展原生元素
- 自治元素(从 HTMLElement 扩展)
- 定制的内置元素(从任何元素扩展)
但 Apple/WebKit 不会如2016 年所述实施后者:
推荐阅读
- laravel - 调度 laravel 命令
- c++ - Qt Creator 错误:找不到 -lopencv_imgcodecs
- java - 如何从 apache http 客户端响应中删除服务器/软件信息
- xml - XSLT:基于子节点属性的排序不起作用
- python - 组合由重叠的低部分和高部分组成的数字
- javascript - 从下拉列表中选择多个选中的值,并在这些值旁边显示一个文本框
- mysql - 仅选择 JOIN 语句中的最后一条记录
- php - PHP:数组格式化
- android - RxSearchView 不支持 androidx SearchView?
- handlebars.js - 如何设置 {{#each }} 来自助手的迭代值