Open wuyuedefeng opened 3 years ago
将dom渲染到shadow dom内
export default { mounted() { const parentElement = this.$el.parentElement const fragment = document.createDocumentFragment() fragment.appendChild(this.$el) const shadowroot = parentElement.attachShadow({ mode: 'open' }) shadowroot.appendChild(fragment) } }
拷贝样式
document.querySelectorAll('head > style[type="text/css"]').forEach(style => { const innerText = style.innerText if (/^(\.np--|\/\*\!.normalize)/.test(innerText)) { // 根据自己要求拷贝全局样式到shadow dom内 // head.appendChild(style) head.appendChild(style.cloneNode(true)) } })
--- 参考资料
完整实现
export default { mounted () { // 创建shadow dom const parentElement = this.$el.parentElement const fragment = document.createDocumentFragment() // const head = document.createElement('head') // fragment.appendChild(head) fragment.appendChild(this.$el) const shadowRoot = parentElement.attachShadow({ mode: 'open' }) shadowRoot.appendChild(fragment) const sheet = new CSSStyleSheet() // 拷贝样式 // document.querySelectorAll('head > style[type="text/css"]').forEach(style => { // head.appendChild(style.cloneNode(true)) // }) // 拷贝样式 document.styleSheets.forEach(stylesheet => { stylesheet.cssRules.forEach(rule => { if (rule.selectorText/* && /^(\.np--|[a-z])/i.test(rule.selectorText) */) { sheet.insertRule(rule.cssText) } }) }) shadowRoot.adoptedStyleSheets = [sheet] // 添加自定义新样式 sheet.insertRule(` a { outline: 2px dashed #f3d500; }`, 0) } }
将dom渲染到shadow dom内
拷贝样式
--- 参考资料
完整实现