我试图将一个类添加到自定义元素,并且正在添加该类(在检查元素时已确认),但是样式并未(再次在检查时确认)。我在这里做错了什么? 这是我的模板代码:
<template id="callInNotification">
<style>
:host {
width: 220px;
height: 85px;
border-radius: 4px;
background-color: #ffffff;
display: flex;
flex-flow: row nowrap;
justify-content: space-between;
align-items: center;
position: fixed;
bottom: 75px;
left: 15px;
opacity: 0;
transform: translateX(-300px);
transition: 250ms all;
cursor: pointer;
}
:host::before {
content: "Incoming Call";
background-repeat: no-repeat;
background-position-y: 15px;
background-image: url(/assets/icons/phone-actions-ring.svg);
background-position-x: center;
background-size: 27px;
height: 85px;
width: 60px;
display: flex;
align-items: flex-end;
background-color: #2485e1;
font-size: 12px;
font-weight: 700;
line-height: 14px;
text-align: center;
color: #ffffff;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
:host.shown {
opacity: 1;
transform: translateX(0px);
}
:host .shown {
opacity: 1;
transform: translateX(0px);
}
</style>
</template>
这是自定义元素代码(字符串“ here”正被记录到控制台):
class CallIn extends HTMLElement {
constructor() {
super();
// get stuff
const template:HTMLTemplateElement = document.getElementById('callInNotification');
const templateContent = template.content;
const shadowRoot:ShadowRoot = this.attachShadow({mode: 'open'})
.appendChild(templateContent.cloneNode(true));
}
connectedCallback(): void {
this.classList.add("shown");
console.log('here');
}
}
customElements.define('call-in', CallIn);
实际上是在这里调用代码的地方:
const newEle = document.createElement("call-in");
newEle.classList.add("shown");
奇怪的是,当我将样式直接添加到这样的元素时:
newEle.style.opacity =“ 1”;
newEle.style.transform =“ translateX(0px)”;
样式生效。
在这里我犯了错,我的自定义元素未应用我班级的样式?
答案 0 :(得分:0)
好吧...我会回答我自己的问题。归功于这篇文章:
https://alligator.io/web-components/styling-custom-elements/
如果要将类添加到您的:host中,则需要采用以下方式:
:host(.shown) {
/*styles*/
}