【问题标题】:Web Components - extend native element's styleWeb Components - 扩展原生元素的样式
【发布时间】:2019-12-20 21:06:42
【问题描述】:

我想扩展原生按钮元素,但不知道如何添加样式。在 Google 的示例 here 中,他们不使用模板,因此 fancy-button 自定义元素本身就是按钮,而不是添加包含按钮元素的模板和阴影 DOM。如果我只是直接向影子 DOM 添加一个按钮,似乎会破坏扩展原生元素的对象,但我不知道如何设置和扩展原生元素。如何创建一个自定义元素,它只是扩展为具有红色背景的本机按钮元素?

var style = `button { background-color: red; };
class FancyButton extends HTMLButtonElement {
  constructor() {
    super();
  }
customElements.define('fancy-button', FancyButton, {extends: 'button'});

【问题讨论】:

    标签: html css web-component native-web-component


    【解决方案1】:
    1. 由于您不涉及 shadowDOM,您可以使用全局 CSS
    2. 可以在connectedCallback中设置样式:this.style.background='red'
    3. 您可以动态地创建一个 STYLE 标记,并使用唯一标识符限定您的元素

    所有 3 个示例请参见 JSFiddle:https://jsfiddle.net/CustomElementsExamples/Lf829wpy/

    重要的是您的自定义内置元素

    的符号

    正确: <button is="fancy-button></button>

    不正确: <fancy-button></fancy-button>(这是自主元素表示法)

    .

    Firefox 陷阱:

    INcorrect 表示法在 Firefox 中有效,但在 Chrome 和 Opera 中

    Firefox 处理 Extended Built-In Elements 使用 Autonomous Element 表示法
    适用于 在定义之前在 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 中显示为:

    • SCRIPT 标记之前的任意数量的自定义元素被着色!

    • &lt;SCRIPT&gt; 移动到&lt;HEAD&gt; 时,Firefox 不会为任何背景着色

    • onload事件之后执行脚本时所有按钮都被着色

    这是非标准行为!

    【讨论】:

    • 使用附加样式表更改组件的innerText 会删除样式表。 jsfiddle.net/yj6Lg3w2/4
    • 是的。这与在 中只有一个
    猜你喜欢
    • 2019-10-30
    • 2019-09-10
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2019-12-21
    • 2019-12-21
    相关资源
    最近更新 更多