我想在我的影子DOM中使用Tippy.js。
由于脚本可以访问我的影子 DOM,但样式不能,我尝试在影子 DOM 中内联 Tippy CSS,并将 Popper 和 Tippy 的 JS 链接到外部。这是它不起作用的演示。
我需要对 CSS 进行限定范围,因此我有以下约束:
<style>
:host {
all: initial; /* 1st rule so subsequent properties are reset. */
display: block;
contain: content; /* Boom. CSS containment FTW. */
/* any other CSS, so this is where I inlined the Tippy's */
}
</style>
对于从谷歌来到这里并徘徊的人来说,将 tippy 放入影子 dom 的当前过程是什么(例如,与浏览器扩展一起使用(。以下内容对我有用:
const shadowRoot = initShadowRoot()
function initShadowRoot() {
const shadowContainer = document.createElement("div")
const shadowRoot = shadowContainer.attachShadow({mode: "open"})
let style = document.createElement('style')
style.innerText = shadowCss // inline or use a bundler to give you a string representation
shadowRoot.appendChild(style)
document.body.appendChild(shadowContainer)
return shadowRoot
}
//---
//elsewhere when initializing tippy:
tippy(elment, {
// ...
// in shadow dom to avoid affecting the page styles
appendTo: () => shadowRoot,
//...
})
获取目标元素,创建一个 style
标记来保存内联 CSS,并将样式标记追加为子元素。
const anchor = document.querySelector('#blog-header')
const style = document.createElement('style')
style.type = 'text/css'
const stylesheet = // inline Tippy.js CSS here or fetch it from somewhere else
style.appendChild(document.createTextNode(stylesheet))
anchor.content.prepend(style)