首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >web组件中的动态样式表添加

web组件中的动态样式表添加
EN

Stack Overflow用户
提问于 2021-02-02 17:01:22
回答 1查看 33关注 0票数 0

我正在尝试创建一个简单的web组件。

代码语言:javascript
复制
const template = document.createElement('template');
template.innerHTML = `
    <style>
        h3 {
            color: coral;
        }
    </style>
    <div class="card" style="width: 18rem;">
        <img class="card-img-top" />
        <div class="card-body">
            <h5 class="card-title">Card title</h5>
            <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
            <a href="#" class="btn btn-primary">Go somewhere</a>
        </div>
    </div>
`;

addStyle(`https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css`);

class UserCard extends HTMLElement {
    constructor() {
        super();

        this.attachShadow({mode: 'open'});
        this.shadowRoot.appendChild(template.content.cloneNode(true));
        this.shadowRoot.querySelector('h5').innerText = this.getAttribute('name');
        this.shadowRoot.querySelector('img').src = this.getAttribute('avatar');

    }
}

window.customElements.define('user-card', UserCard);

function addStyle(href) {              
    var link = document.createElement('link');
    link.id = 'id2';
    link.rel = 'stylesheet';
    link.href = href;
    document.head.appendChild(link); 
} 

我可以看到在head中添加了样式表,但是bootstrap card css不工作。

请帮帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-02 17:21:52

Shadow DOM阻止文档级CSS应用于阴影根-这是web组件的整个概念:它们允许您部署一个容器化组件,该组件受到保护,不受文档中应用的样式和布局更改的影响。这是一个特性,而不是一个bug。

要将样式应用于web组件,需要将样式附加到阴影根本身。有关详细信息,请参阅上面的参考资料,但通常我会像这样实现您的代码:

代码语言:javascript
复制
class UserCard extends HTMLElement {
    styleURL = 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css';
    constructor() {
        super();

        this.attachShadow({mode: 'open'});
        this.shadowRoot.appendChild(template.content.cloneNode(true));
        this.shadowRoot.querySelector('h5').innerText = this.getAttribute('name');
        this.shadowRoot.querySelector('img').src = this.getAttribute('avatar');

        let style = document.createElement('style');
        style.textContent = `@import url("${this.styleURL}");`
        this.shadowRoot.appendChild(style);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66006486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档