我正在尝试创建一个简单的web组件。
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不工作。
请帮帮忙。
发布于 2021-02-02 17:21:52
Shadow DOM阻止文档级CSS应用于阴影根-这是web组件的整个概念:它们允许您部署一个容器化组件,该组件受到保护,不受文档中应用的样式和布局更改的影响。这是一个特性,而不是一个bug。
要将样式应用于web组件,需要将样式附加到阴影根本身。有关详细信息,请参阅上面的参考资料,但通常我会像这样实现您的代码:
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);
}
}https://stackoverflow.com/questions/66006486
复制相似问题