2014-09-22 69 views
0

我創建了一個帶有陰影dom的元素,最終用於自定義元素。我的HTML文件已經有點臃腫了,所以我最好喜歡將我的所有模板移動到java腳本中,而不是在我的html主體中引用模板。在javascript中定義陰影DOM模板

我試過這個方法這樣做:

var template = document.createElement('template'), 
    div = document.createElement('div'); 

div.textContent = 'foo'; 
template.appendChild(div); 

var shadow = document.body.appendChild('div').createShadowRoot(); 

shadow.appendChild(template.content.cloneNode()); 

但是,這將引發一個NotFoundError。挖掘更深入,它看起來像template.content只是定義爲#documentFragment,這似乎可能是問題,但我不知道足夠的陰影dom或模板來說肯定。

有沒有在我的代碼中的錯誤或更好的方式在JavaScript中創建模板?

Here is my test fiddle.

回答

2

首先,這個調用是無效的:

document.body.appendChild('div') 

你需要DOM中的常規元素,爲了安裝影子DOM:

var mountingPoint = document.createElement('div'); 
document.body.appendChild(mountingPoint); 

一個<template>是包含名爲content的文檔片段的元素:

此接口也適用於Web組件:<模板>元素在其HTMLTemplateElement.content屬性中包含DocumentFragment。 (Source: MDN

所以,你可以替換template.appendChild(div);有:

template.content.appendChild(div); 

也要注意,使用瀏覽器,該方法cloneNode的第一個參數deep必須true因爲default is false

template.content.cloneNode(true); 

但是,您不需要<template>元素。直接使用創建的DIV:

var div = document.createElement('div'); 
div.textContent = 'foo'; 

var mountingPoint = document.createElement('div'); 
document.body.appendChild(mountingPoint); 

var shadow = mountingPoint.createShadowRoot(); 
shadow.appendChild(div);