我想扩展 native 按钮元素,但我不确定如何添加样式。在谷歌的例子中 here他们不使用模板,所以 fancy-button
自定义元素本身就是按钮,而不是添加包含按钮元素的模板和影子 DOM。如果我只是直接向影子 DOM 添加一个按钮,这似乎打败了扩展 native 元素的目标,但我不知道如何设置和扩展 native 元素。我如何创建一个自定义元素,它只是扩展为具有红色背景的原生按钮元素?
var style = `button { background-color: red; };
class FancyButton extends HTMLButtonElement {
constructor() {
super();
}
customElements.define('fancy-button', FancyButton, {extends: 'button'});
最佳答案
- 因为您没有涉及 shadowDOM,所以您可以使用全局 CSS
- 您可以在 connectedCallback 中设置样式:
this.style.background='red'
- 您可以动态创建一个带有唯一标识符的 STYLE 标签,为您的元素划定范围
有关所有 3 个示例,请参见 JSFiddle:https://jsfiddle.net/WebComponents/gohzwvL4/
Important is the notation for your Customized Built-In Element
正确: <button is="fancy-button></button>
错误: <fancy-button></fancy-button>
(这是自治元素表示法)
.
Firefox 陷阱:
不正确 符号在 Firefox 中有效,但在 Chrome 和 Opera 中不
Firefox 使用Autonomous Element 符号处理Extended Built-In Elements
但仅定义之前在DOM中创建的元素:
这个
<fancy-button>Hello Fancy Red Button #1</fancy-button>
<script>
class FancyButton extends HTMLButtonElement {
constructor() {
super();
}
connectedCallback() {
this.style.background = 'red';
}
}
customElements.define('fancy-button', FancyButton, { extends: 'button' });
</script>
<fancy-button>Hello Fancy Red Button #2</fancy-button>
在 Firefox 中显示为:
any number of Custom Elements before the
SCRIPT
tag are colored!When the
<SCRIPT>
is moved into the<HEAD>
Firefox won't color any backgroundWhen the script is executed after the
onload
event all buttons are colored
这是非标准行为!
关于html - Web Components - 扩展原生元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431342/