样式相关术语

  • :host: 指向宿主元素。但是!
  1. /* winner */
  2. custom-picture {
  3. background: red;
  4. }
  5. /* loser */
  6. #shadow-root
  7. <style>
  8. :host {
  9. background: green;
  10. }
  11. </style>
  • :host(<selector>): 组件 hostselector 是匹配的么?基本上是对同一个宿主的不同状态。举例如下:
  1. :host([disabled]) {
  2. ...;
  3. }
  4. :host(:focus) {
  5. ...;
  6. }
  7. :host(:focus) span {
  8. /*change all spans inside the element when the host has focus*/
  9. }
  • :host-context(<selector>): hostselector 选择器的后代元素么?让我们根据父元素的样式来改变组件的样式,一般应用在各种主题上。
  1. :host-context(.light-theme) {
  2. background: lightgray;
  3. }
  4. :host-context(.dark-theme) {
  5. background: darkgray;
  6. }
  7. /*You can also do...*/
  8. :host-context(.aqua-theme) > * {
  9. color: aqua; /* lame */
  10. }

关于 :host() 和 :host-context() 的笔记

两个伪类函数只能使用 <compound-selector> 复合选择器,不能使用空格或者‘>’或者’+’等组合符

对于 :host() 意味着你只能在宿主元素内部选择属性操作.

对于 :host-context() 意味着你能选择一个特定 :host 祖先的元素,只能选一个!

attachShadow() 中的模式会影响样式的应用或者层叠么?

不会的!仅仅影响我们的JavaScript的使用。

用户代理样式如何应用到 shadow DOM 元素上?

基于shadow root或者普通的文档碎片,用户代理样式(全局)不应该应用到shadow root内的所有元素。所以,他们如何运行的呢?

根据专业文档…

Windows gain a private slot [[defaultElementStylesMap]] which is a map of local names to stylesheets. This makes it possible to write elements inside shadow root and still get the default browser styles applied to them.

哪些样式可以放进shadow DOM ?

shadow DOM 中设定了默认样式,并通过 CSS 自定义属性提供钩子,这样组件用户就可以通过 CSS 自定义属性(也就是 CSS 变量)修改这些默认样式。

  1. <business-card>
  2. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  3. #shadow-root
  4. <h1 class="card-title">Hardcoded Title - </h1>
  5. ---------------------------------------------------
  6. </business-card>
  1. /*inside shadow DOM*/
  2. .card-title {
  3. color: var(--card-title-color, #000);
  4. }
  5. /* Component users can then override this color as*/
  6. business-card {
  7. --card-title-color: magenta;
  8. }

阅读专业文档中的笔记

  • 一个shadow host 是在他存在的宿主环境的 shadow tree之外的,因此通常不会被任何shadow tree的上下文选择器所命中(因为选择器受限于单个树) ,但是有时候能够在 shadow tree 上下文中创建样式是很有用的。
  • 为了解决这个问题,shadow host被用来替代shadow root节点。
  • 当考虑到本身的shadow trees时候,shadow host是没有任何特色的,只允许 :host, :host(), and :host-context() 伪类与之匹配。