css样式隔离
使用 浏览器的api实现,有个缺点 如果挂载到body上就会产生一些影响
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><div><p>孤独的p</p><div id="shadow"></div></div><p>审查元素的时候就会看到 shadowDOM是 名为shadow的影子,外界是无法访问的的</p></body></html><script>/*** css 样式隔离*/// open 外界可以访问 closed 外界不能访问let shadowDOM = document.getElementById('shadow').attachShadow({ mode: 'closed' });// 外界无法访问的shadow domlet pEl = document.createElement('p');pEl.innerHTML = "shadowDOM";let styleEl = document.createElement('style');styleEl.textContent = `p{color:red}`shadowDOM.appendChild(styleEl);shadowDOM.appendChild(pEl);// 纯在一个问题 ,如果把这些放到body上后 就会有影响// document.body.appendChild(pEl)</script>
