ShingoFukuyama
4/16/2015 - 2:48 PM

Web製作者のためのCSS設計の教科書 p198 Web Components

Web製作者のためのCSS設計の教科書 p198 Web Components

<!DOCTYPE html>
<html>

  <head>
  </head>

  <body>

    <my-alert></my-alert><!-- custom element -->

    <template id="my-alert-template">

      <style>
       .alert {
         position: relative;
         border-radius: 6px;
         border: 1px solid #ddd;
         background-color: #eee;
         padding: 0.6em 0.6em;
       }

       .alert__title,
       .alert__body > * {
         margin: 0;
         padding: 0;
       }

       .alert__title {
         font-weight: bold;
       }
      </style>

      <div class="alert">
        <p class="alert__title">Alert Title</p>
        <div class="alert__body">
          <p>Message</p>
        </div>
      </div>

    </template>

    <script>
     (function() {
       var element = Object.create(HTMLElement.prototype);

       // Run when custom elements created
       element.createdCallback = function() {
         var template = document.querySelector('#my-alert-template');
         var content = template.content;
         var shadowRoot = this.createShadowRoot();
         shadowRoot.appendChild(document.importNode(content, true));
       };

       // Register my-alert tag and inherit the object created above
       document.registerElement('my-alert', {
         prototype: element
       });

     })();
    </script>

  </body>
</html>