2
我製作了一個非常基本的Web組件。我使用自定義元素構造函數編寫的JavaScript添加和刪除類。添加/刪除在陰影DOM中定義的類
爲什麼當我將文檔的樣式表中的類移動到自定義元素的影子DOM中的樣式表時,我的javascript不再能夠添加或刪除它們?
class BgAnim extends HTMLElement {
constructor() {
super()
this.attachShadow({
mode: 'open'
})
this.shadowRoot.innerHTML =
`
<style>
:host {
background-image: linear-gradient(#0fe0e0 0%, #0fe0e0 50%, transparent 50%, transparent 100%);
background-size: 100% 200%;
background-repeat: no-repeat;
background-position: 0 100%;
padding: 4px;
}
</style>
<span><slot></slot></span>
`
this.addEventListener('mouseenter', function() {
this.classList.add('transition')
this.classList.add('bg-position0')
})
this.addEventListener('mouseleave', function() {
this.classList.add('bg-position-negative')
var that = this
setTimeout(function() {
that.classList.remove('transition')
that.classList.remove('bg-position0')
that.classList.remove('bg-position-negative')
}, 510)
})
}
}
customElements.define('bg-anim', BgAnim)
,我想添加和刪除與我的JavaScript是風格
.transition {
transition: background-position .5s ease-in;
}
.bg-position0 {
background-position: 0 0%;
}
.bg-position-negative {
background-position: 0 -100%;
}
當他們在陰影DOM我的JS不起作用:
this.shadowRoot.innerHTML =
`
<style>
.transition {
transition: background-position .5s ease-in;
}
.bg-position0 {
background-position: 0 0%;
}
.bg-position-negative {
background-position: 0 -100%;
}
:host {
background-image: linear-gradient(#0fe0e0 0%, #0fe0e0 50%, transparent 50%, transparent 100%);
background-size: 100% 200%;
background-repeat: no-repeat;
background-position: 0 100%;
padding: 4px;
}
</style>
<span><slot></slot></span>
`