【发布时间】:2017-11-21 17:51:39
【问题描述】:
我有以下本地 html:
<html>
<head>
<link rel="import" href="https://mygithub.github.io/webcomponent/">
</head>
<body>
<!-- This is the custom html component I attempted to create -->
<img-slider></img-slider>
</body>
</html>
以及以下对模板的尝试:
<template>
<style>
.redColor{
background-color:red;
}
</style>
<div class = "redColor">The sky is blue</div>
</template>
<script>
// Grab our template full of slider markup and styles
var tmpl = document.querySelector('template');
// Create a prototype for a new element that extends HTMLElement
var ImgSliderProto = Object.create(HTMLElement.prototype);
// Setup our Shadow DOM and clone the template
ImgSliderProto.createdCallback = function() {
var root = this.createShadowRoot();
root.appendChild(document.importNode(tmpl.content, true));
};
// Register our new element
var ImgSlider = document.registerElement('img-slider', {
prototype: ImgSliderProto
});
</script>
如this article 中所述。当我运行代码时,我得到:
未捕获的类型错误:无法读取 null 的属性“内容” 在 HTMLElement.ImgSliderProto.createdCallback ((index):20)
换句话说,document.querySelector('template'); 返回 null。什么给了?
我的目标是创建自定义 html 元素并将其显示在链接模板代码的网站上。我 100% 确定我正确地提取了远程模板代码(显然,因为我在该代码中得到了错误)。
附:我使用的是最新的 Chrome,所以我不需要 polyfill。
【问题讨论】:
标签: javascript html css templates web-component