简体   繁体   English

样式化Web组件中的封闭DOM节点

[英]Styling the enclosing DOM node in Web Components

I have defined a type-extension custom element as follows: 我已经定义了一个类型扩展自定义元素,如下所示:

(function() {
    'use strict';

    var importDoc, myButton;

    importDoc = document.currentScript.ownerDocument;
    myButton = Object.create(HTMLButtonElement.prototype);

    myButton.createdCallback = function() {
        var template, templateClone, shadow, host;

        template = importDoc.querySelector('#my-button-large-template');
        templateClone = importDoc.importNode(template.content, true);

        host = this;
        shadow = this.createShadowRoot();
        shadow.appendChild(templateClone);
    };

    document.registerElement('my-button', {
        prototype: myButton,
        extends: 'button'
    });

}());

The declaration in the DOM looks like this: DOM中的声明如下所示:

<button is="my-button">Foo</button>

But the button retains the default button styling of the browser (a grey gradient background and an embossed effect). 但是该按钮保留了浏览器的默认按钮样式(灰色渐变背景和浮雕效果)。

Can I remove this styling from the element from within the web component itself ? 我可以从Web组件本身内部的元素中删除此样式吗?

Put another way, does the host DOM have to contain styling to neuter the browser stylesheet as applied to web components that extend native elements? 换句话说,宿主DOM是否必须包含样式以使浏览器样式表中止应用于扩展本机元素的Web组件?

For a button element, user agent styles are applied to the element itself (as opposed to its shadow DOM, as with elements like audio ) so that's where you'd need to style it. 对于button元素,用户代理样式将应用于该元素本身(与其阴影DOM相反,与诸如audio元素一样),因此需要在其中进行样式设置。 You can, however, style the custom button from inside its shadow DOM with the :host selector: 但是,您可以使用:host选择器从其影子DOM内部设置自定义按钮的样式:

myButton.createdCallback = function() {
    var shadow, host;

    host = this;
    shadow = this.createShadowRoot();
    shadow.innerHTML = '<style>:host { color: red; } </style><content></content>';
};

Or you can style the custom button as you would any normal element, but from inside the createdCallback : 或者,您可以像对任何常规元素一样设置自定义button样式,但可以从createdCallback内部:

myButton.createdCallback = function() {
    this.style.color = 'red';
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM