WebComponents001
Sample1: ShadowDom 隔离style,替换显示内容
<button>Hello, world!</button> <script> var host = document.querySelector('button'); var root = host.createShadowRoot(); root.innerHTML = '<style>div{background-color : blue;}</style> <div>Hi, you are great!</div>'; </script> <style> div { background-color : green; } </style> <div>Outside Element</div>
Sample 2: 通过Template给shadow Dom设置内容, 注意template中的script的作用域是全局的,style的作用域是shadow dom局部
<button>Hello, world!</button>
<div>Outside Element</div> <template id="t1"> <style>div{background-color : blue;}</style> <div>Hi, you are great!</div> <script> //此处脚本不会被执行 var d = document.querySelector('div'); d.onclick = function(){ alert("Hi"); } </script> </template> <script> var host = document.querySelector('button'); var root = host.createShadowRoot(); var t = document.querySelector("#t1"); //通过innerHTML给shadow dom赋值,不会执行template中的script root.innerHTML = t.innerHTML; </script> <style> div { background-color : green; } </style>
Sample 3: 为template中的content嵌入子节点。子节点的style受外部css的直接控制,但是会继承shadow dom中父节点的style
<div id="hostNode"><div>Hello, world!</div></div> <div>Outside Element</div> <template id="t1"> <style>div{background-color : blue; font-size: 30px;}</style> <div>Hi, you are great!</div> <div> <content></content> </div> </template> <script> var host = document.querySelector('#hostNode'); var root = host.createShadowRoot(); var t = document.querySelector("#t1"); var content = t.content; root.appendChild(document.importNode(content,true)); </script> <style> div { background-color : green; font-size: 40px; } #mytext { background-color : red; } </style>
sample 4:带有select的content
<div id="hostNode"> <div class="kk">Hello, kk world!</div> <div class="hh">Hello, hh world!</div> </div> <div>Outside Element</div> <template id="t1"> <style>div{background-color : blue; font-size: 30px;}</style> <div>Hi, you are great!</div> <div> <content select=".hh"></content> 分割<br> <content select=".kk"></content> </div> </template> <script> var host = document.querySelector('#hostNode'); var root = host.createShadowRoot(); var t = document.querySelector("#t1"); var content = t.content; root.appendChild(document.importNode(content,true)); </script> <style> div { background-color : green; font-size: 40px; } #mytext { background-color : red; } </style>