Web组件-扩展本机元素的样式 [英] Web Components - extend native element's style
问题描述
我想扩展本机按钮元素,但是我不确定如何添加样式.在Google的示例此处中,他们不使用模板,因此fancy-button
定制元素本身就是按钮,而不是添加包含按钮元素的模板和阴影DOM.如果仅将按钮直接添加到阴影DOM中,似乎无法实现扩展本机元素的目标,但是我不知道如何设置本机元素的样式和扩展.如何创建一个自定义元素,该元素只是将本机按钮元素扩展为具有红色背景?
I would like to extend the native button element but I am not sure how to add styling. In Google's example here they don't use a template so the fancy-button
custom element itself is the button, rather than adding a template and shadow DOM containing a button element. It seems to defeat the object of extending a native element if I just add a button directly to the shadow DOM, but I don't know how to style and extend native element. How can I create a custom element which is simply the native button element extended to have a red background?
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/CustomElementsExamples/Lf829wpy/
See JSFiddle for all 3 examples: https://jsfiddle.net/CustomElementsExamples/Lf829wpy/
重要是您的自定义内置元素
正确: <button is="fancy-button></button>
不正确: <fancy-button></fancy-button>
(这是自治元素表示法)
InCorrect: <fancy-button></fancy-button>
(this is Autonomous Element notation)
.
不正确表示法在Firefox中有效,而不是在Chrome&歌剧
The INcorrect notation works in Firefox , but not in Chrome & Opera
Firefox用自治元素表示法处理扩展的内置元素
但仅用于在先于定义的DOM中创建的元素:
Firefox processes Extended Built-In Elements with Autonomous Element notation
but only for elements created in the DOM prior to definition:
此
<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中显示为:
is displayed in Firefox as:
之前任意数量的自定义元素都已着色
SCRIPT
标签!
any number of Custom Elements before the
SCRIPT
tag are colored!
将<SCRIPT>
移入<HEAD>
后,Firefox不会为任何背景着色
When the <SCRIPT>
is moved into the <HEAD>
Firefox won't color any background
在onload
事件后执行脚本时,所有按钮均已着色
When the script is executed after the onload
event all buttons are colored
这是非标准行为!
这篇关于Web组件-扩展本机元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!