shadowDom中mode取不同值的区别

2019-10-31  本文已影响0人  videring
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>shadowDom 示例</title>
<script>
const template = document.createElement('template');
template.innerHTML = `
  <style>
    .container {
      padding: 8px;
    }
    button {
      display: block;
      overflow: hidden;
      position: relative;
      padding: 0 16px;
      font-size: 16px;
      font-weight: bold;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
      outline: none;
      width: 100%;
      height: 40px;
      box-sizing: border-box;
      border: 1px solid #a1a1a1;
      background: #ffffff;
      box-shadow: 0 2px 4px 0 rgba(0,0,0, 0.05), 0 2px 8px 0 rgba(161,161,161, 0.4);
      color: #363636;
      cursor: pointer;
    }
  </style>
  <div class="container">
    <button>Label</button>
  </div>
`;
var modeStatus = 'open' 
class Button extends HTMLElement {
  constructor() {
    super();
    this._shadowRoot = this.attachShadow({ mode: modeStatus });
    this._shadowRoot.appendChild(template.content.cloneNode(true));
  }
}
window.customElements.define('my-button', Button);
    function display () {
        let sD = document.querySelector('my-button')
        if (modeStatus === 'open') { // 关键
            sD.shadowRoot.querySelector('.container').style.background = 'red'
        }
    }
</script>
</head>
<body>
<button id='outerBtn' type="button" onclick="display()">修改shadowDom背景色</button>
<my-button>aaa</my-button>
</body>
</html>

如上例,如果modeStatus设置成closed,sD.shadowRoot将返回null,也就无法操作shadowDom;如果设置成open,那么在外部可以获取shadowDom中的样式和元素,甚至修改。

参考:Using_shadow_DOM

上一篇下一篇

猜你喜欢

热点阅读