写一个方法,分别把v-html的代码进行拆分、分为html和css:
const transitionClass: any = (html = "", css = "") => {
let res = html.match(new RegExp('style="(.*?)"'));
if (res) {
// 随机ID
const id = Math.random().toString().slice(2);
css += `.${id}{${res[1]}}\n`;
html = html.replace(new RegExp('style=".*?"'), `class="${id}"`);
return transitionClass(html, css);
} else {
return { html, css };
}
};
然后调用刚刚定义的方法。
定义一个shadow对象,
然后创建dom和样式实例,
最后append到刚刚定义的shadow对象中,
const { html, css } = transitionClass(model.value.html);
var richShadow = richText.value.attachShadow({ mode: "open" });
let richTextDom = document.createElement("p");
richTextDom.innerHTML = html;
let richTextStyle = document.createElement("style");
richTextStyle.textContent = css;
richShadow.appendChild(richTextStyle);
richShadow.appendChild(richTextDom);