webcomponent學習筆記(一)
- 2019 年 12 月 4 日
- 筆記
本文作者:IMWeb 黃龍 原文出處:IMWeb社區 未經同意,禁止轉載
webcomponent是一個新的瀏覽器功能,為web提供了一個標準組件模型,包括以下幾個部分:
- Shadow DOM
- Custom Elements
- HTML Imports
- HTML Templates
Shadow DOM是什麼
直接翻譯是 影子文檔對象模型。
定義:Shadow DOM 是一個 HTML 的新規範,其允許開發者封裝自己的 HTML 標籤、CSS 樣式和 JavaScript程式碼。 使得開發人員可以自定義諸如 <input type="range">
這樣的一級標籤。
我們就用range組件來來解釋Shadow DOM
<input type="range">
打開Chrome的開發者工具,點擊右上角的"Settings"按鈕,

勾選「Show user agent shadow DOM」,

你就可以看到range組件的DOM結構的細節。

你會發現,瀏覽器內部實現range組件也是通過定義dom結構來實現的。 看到標灰的 #shadow-root 了嗎?這裡就是所有影片播放器控制組件的所在之處。瀏覽器之所以將其置灰,是為了表明這部分是在 shadow DOM 里,對於頁面的其他部分來說它是不可用的。這裡的不可用意味著你寫的 CSS 選擇器和 JavaScript程式碼都不會影響到這部分內容。
必須的HelloWorld
可以戳這裡 http://git.360rush.com/demo/shadowDom/helloworld.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shadow DOM -- Hello World</title> </head> <body> <div class="hi">你好Shadow DOM!</div> <script> var hi = document.querySelector('.hi'); var shadowRoot = hi.createShadowRoot(); var dom = document.createElement('p'); dom = '《<content></content>》'; shadowRoot.appendChild(dom); </script> </body> </html>
結果是這樣子的

我們在helloworld中使用<content>
標籤,它的作用是在Shadow DOM中使用宿主的內容。
那麼我能只顯示其中一部分的內容嗎? 答案是可以得,我們來看看下面的例子 http://git.360rush.com/demo/shadowDom/contentSelector.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Shadow DOM -- contentSelector</title> </head> <body> <helloworld> <span class="name">lonnyhuang</span> <span class="sex">男</span> <span class="city">深圳</span> </helloworld> <script type="tpl" class="sd-helloworld"> <style> p { line-height: 20px; margin: 0; } </style> <p>姓名:<content select=".name"></content></p> <p>性別:<content select=".sex"></content></p> <p>所在城市:<content select=".city"></content></p> </script> <script> var host = document.querySelector('helloworld'); var shadowRoot = host.createShadowRoot(); shadowRoot = document.querySelector('.sd-helloworld'); </script> </body> </html>

這裡要用到<content>
標籤的select
屬性。為了方便這裡直接用script標籤做模板。可以看到對應的標籤映射到了select選擇器對應的位置
這裡僅僅簡單介紹了Shadow DOM的v0版本api。有人總結了v1版本和v0的不同點。其中提到也可以用slot
來做選擇宿主的子節點的選擇器,試了一下我的chrome還沒有支援 地址在這裡:http://hayato.io/2016/shadowdomv1/