html - Web Components - 扩展原生元素的样式

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

我想扩展 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'});

最佳答案

  1. 因为您没有涉及 shadowDOM,所以您可以使用全局 CSS
  2. 您可以在 connectedCallback 中设置样式:this.style.background='red'
  3. 您可以动态创建一个带有唯一标识符的 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 background

  • When the script is executed after the onload event all buttons are colored

这是非标准行为!

关于html - Web Components - 扩展原生元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431342/

相关文章:

javascript - 从包含 Web 组件的插槽内容中捕获事件

javascript - 清理自定义元素中的事件监听器

javascript - 如何将 JSON 对象存储为 select 标签中的选项值?

javascript - 使用表单的下一个和上一个按钮的 Bootstrap 选项卡

jQuery 以 CSS 为目标 a :hover class

javascript - Polymer 1.x 和 React

html - 如何使用 Flex-box 进行响应式元素布局?

javascript - Spotify api javascript 验证创建播放列表

html - Bootstrap 的新手 - 有一些移动样式问题

jquery - 悬停包装器上的 css 显示和滑动 div