我正在尝试创建一个扩展 div 元素的 Web 组件,我发现了 this other Stack Overflow question关于如何扩展 native 元素(在本例中为按钮)。但是,我无法使其工作。并且,根据 this answer 中的更新,它应该可以工作。
如果您查看这个简化代码片段中的结果,它只是呈现为带有文本的简单内联元素。 如果您打开 Chrome 控制台并查看属性选项卡,也很明显它不会继承自 HTMLButtonElement(它应该继承)。怎么了?
class FancyButton extends HTMLButtonElement {
constructor() {
super(); // always call super() first in the ctor.
this.addEventListener('click', e => this.innerHTML = "I was clicked");
}
}
customElements.define('fancy-button', FancyButton, { extends: 'button' });
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<fancy-button>Click me</fancy-button>
</body>
</html>
最佳答案
据我所知
有两种类型的自定义元素 MDN: Using Custom Elements
- 自主自定义元素
- 自定义内置元素
Polyfill Safari 需要
因为 Apple... 好吧.. 是 Apple.. 并拒绝实现自定义元素
一个注册管理机构统领一切
只有一个注册表,因此您的自定义元素 注册为fancy-button
;
但是可以NOT*与Autonomous notation:一起使用:<fancy-button></fancy-button/>
* Firefox DOES allow a mix of both notations BUT only if define() is used AFTER element usage
来自文档部分:扩展原生 HTML 元素:
https://developers.google.com/web/fundamentals/web-components/customelements#extendhtml
自定义内置元素的消费者可以通过多种方式使用它。
他们可以通过在原生标签上添加 is=""属性来声明它:
<!-- This <button> is a fancy button. -->
<button is="fancy-button" disabled>Fancy button!</button>
在 JavaScript 中创建一个实例:
// Custom elements overload createElement() to support the is="" attribute.
let button = document.createElement('button', {is: 'fancy-button'});
button.textContent = 'Fancy button!';
button.disabled = true;
// have to do this yourself!! IF you want to use it as a selector
button.setAttribute("is","fancy-button");
document.body.appendChild(button);
或者使用新的运算符:
let button = new FancyButton();
button.textContent = 'Fancy button!';
button.disabled = true;
结论
有两种自定义元素,不能混用
你要么去:
- 自主自定义元素:
<fancy-button></fancy-button>
或
- 自定义内置元素
<button is=fancy-button></button>
用于定制的内置元素
document.createElement('fancy-button') instanceof HTMLButtonElement
返回假
和
<fancy-button>lightDOM</fancy-button>
document.querySelector('fancy-button')
返回元素(如果在 DOM 中),
但该元素被处理为显示 lightDOM 内容的未定义元素
使用两种类型的自定义元素的示例
在https://cardmeister.github.io我同时使用了:
<card-t rank=queen suit=hearts></card-t>
<img is=queen-of-hearts/>
因此我不能做:
<queen-of-hearts></queen-of-hearts>
后者没有什么值(value),用IMG is
属性可用于 CSS 定位。
CSS Selector for a partial CustomElement nodename
关于javascript - Web 组件 : extending native elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619025/