繁体   English   中英

CSS 样式未应用于自定义组件

[英]CSS Style not applied on custom component

我创建了一个自定义 web 组件(没有任何框架)。 然后我用模板标签中的内容填充它。

最后,我使用 Javascript 编辑内容。 这工作正常。 不起作用的是使用 Javascript 编辑 styles。 为什么会这样,如何使用代码在 Web 组件内编辑 CSS?

class GeneratorView extends HTMLElement {

    connectedCallback() {

        // Use a template to fill this component
        const template = document.getElementById('generator-template')
        const templateContent = template.content
        this.appendChild(templateContent)

        // find the label tag in this component
        const label = this.querySelector("#label")

        // THIS WORKS - set the label text
        label.innerText = "The text has changed"

        // THIS DOESN'T WORK - set the label style
        label.style.border = "4px solid red;"
    }
}

customElements.define('generator-view', GeneratorView)

模板看起来像这样

<template id="generator-template">
        <div id="label">
            Change this text
        </div>
</template>

问题是您要在样式中添加分号。

分号仅由 CSS 解析器用于了解 css 值之间的中断。 在最后一个值之后不需要一个,并且在元素的样式属性中设置值时不能使用它们。

我简化了您的代码以进行演示。

用分号

 const template = `<div id="label">Change this text</div>`; class GeneratorView extends HTMLElement { connectedCallback() { this.innerHTML = template; const label = this.querySelector("#label"); label.innerText = "The text has changed"; label.style.border = "4px solid red;" } } customElements.define('generator-view', GeneratorView);
 <generator-view></generator-view>

没有分号

 const template = `<div id="label">Change this text</div>`; class GeneratorView extends HTMLElement { connectedCallback() { this.innerHTML = template; const label = this.querySelector("#label"); label.innerText = "The text has changed"; label.style.border = "4px solid red"; } } customElements.define('generator-view', GeneratorView);
 <generator-view></generator-view>

暂无
暂无

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

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