Как правильно работать с Shadow DOM

Как смотреть

Google Chrome DevTools → Настройки → General → Show Shadow DOM.

Как пользоваться

<template id="musicPlayerTemplate">
  <style>
    .outer {
      width: 350px;
      font-family: Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      border-radius: 5px;
      overflow: hidden;
      box-shadow: 0 1px 3px rgba(0,0,0,0.4);
    }

    .info {
      background: #545454; 
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#545454), color-stop(100%,#212121)); 
      background: -webkit-linear-gradient(top,  #545454 0%,#212121 100%);
      background: linear-gradient(to bottom,  #545454 0%,#212121 100%);
      padding: 1.5em;
      text-align: center;
    }

    .song {
      color: #FFFFFF;
      font-size: 1.5em;
    }

    .artist {
      margin-top: 0.5em;
      color: #BABABA;
      font-size: 0.9em;
    }

    .controls {
      padding: 1em;
      text-align: center;
      background: #f7f7f7;
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f7f7f7), color-stop(100%,#e6e6e6));
      background: -webkit-linear-gradient(top,  #f7f7f7 0%,#e6e6e6 100%);
      background: linear-gradient(to bottom,  #f7f7f7 0%,#e6e6e6 100%);
    }

    button {
      background: #f9f9f9;
      background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f9f9f9), color-stop(100%,#d9d9d9)); 
      background: -webkit-linear-gradient(top,  #f9f9f9 0%,#d9d9d9 100%);
      background: linear-gradient(to bottom,  #f9f9f9 0%,#d9d9d9 100%); 
      border: 1px solid #BABABA;
      border-radius: 3px;
      font-size: 0.8em;
      padding: 0.3em 0.6em;
      cursor: pointer;
    }
  </style>

  <div>
    <div>
      <div>
        <!-- <content select=".song"></content> -->
        Song Name
      </div>
      <div>
        <!-- <content select=".artist"></content> -->
        Artist
      </div>
    </div>
    <div>
      <button>Play</button>
      <button>Pause</button>
    </div>
  </div>
</template>

HTML для использования

<div id="musicPlayer">
  <span>Orange Skies</span>
  <span>Newton Faulkner</span>
</div>

JS для замены:

  var host = document.querySelector('#musicPlayer');
  var shadow = host.webkitCreateShadowRoot();
  var template = document.querySelector('#musicPlayerTemplate');
  shadow.appendChild(template.content);
  template.remove();
</script>

Вот с описанием:
http://blog.teamtreehouse.com/working-with-shadow-dom

LEAVE A COMMENT