Skip to content

Instantly share code, notes, and snippets.

@ykhs
Created July 1, 2012 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ykhs/3027432 to your computer and use it in GitHub Desktop.
Save ykhs/3027432 to your computer and use it in GitHub Desktop.
Shadow DOM Sample
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title></title>
<!-- このスタイルは文書ツリー側に定義したものなので Shadow DOM 内部には適用されない。 -->
<style>
section.articleBox h1 {
color: black;
}
</style>
</head>
<body>
<!-- Original Document Tree -->
<!-- Shadow Host になってもらう要素 -->
<section class="articleBox">
<h1 class="articleBoxTitle">Article Group</h1>
<article class="new">
<h1>New Article</h1>
<p>New!</p>
</article>
<article class="new">
<h1>New Article 2</h1>
<p>New!New!</p>
</article>
<article class="cool">
<h1>Cool Article</h1>
<p>Cool!</p>
</article>
<article>
<h1>Article</h1>
<p>hogehoge</p>
</article>
<article class="cool">
<h1>Cool Article 2</h1>
<p>Cool!Cool!</p>
</article>
<article>
<h1>Article 2</h1>
<p>fugafuga</p>
</article>
</section>
<!-- For Shadow DOM Tree -->
<!-- Shadow DOM Subtree になってもらう要素 -->
<section id="shadow-articleArea">
<!-- このスタイルは Shadow DOM 側に定義したものと扱われるので文書ツリー側には適用されない。 -->
<style scoped>
.shadow-newArticleBox {
padding: 1px 12px;
color: #fcfcfc;
background: #ee9999;
}
.shadow-coolArticleBox {
padding: 1px 12px;
color: #fcfcfc;
background: #0099cc;
}
.shadow-articleBox {
padding: 1px 12px;
color: #fcfcfc;
background: #999;
}
</style>
<!--
Shadow DOM 内に content 要素が存在すると、そこへ Shadow Host となったため
描画されなくなった元々の文書ツリーの内容が流し込まれる。
select 属性に記述したセレクタで流しこむ要素を選択出来る。
-->
<content select="h1.articleBoxTitle"></content>
<section class="shadow-newArticleBox">
<h1>New Articles</h1>
<content select="article.new"></content>
</section>
<section class="shadow-coolArticleBox">
<h1>Cool Articles</h1>
<content select="article.cool"></content>
</section>
<section class="shadow-articleBox">
<h1>Articles</h1>
<content select="article"></content>
</section>
</section>
<script>
/*
* Get Document Tree Element
* (文書ツリーの DOM を取得)
*/
var documentElement = document.querySelector('section.articleBox');
/*
* Create Shadow DOM Root
* (取得した DOM の配下にシャドウルートを生成)
*
* この時点で section.articleBox はシャドウホストとなり、自身が元々持っていた
* 子要素は描画されない。
*/
var shadowRoot = new WebKitShadowRoot(documentElement);
/*
* Get Document Tree for create a Shadow Subtree.
* (シャドウツリー用に書いておいた要素を取得)
*/
var shadowSubtree = document.querySelector('#shadow-articleArea');
/*
* Create Shadow Subtree.
* (これをシャドウルートに挿入してシャドウツリーを生成)
*/
shadowRoot.appendChild(shadowSubtree);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment