我想制作一个自定义元素,它将在html导入时自动注册。
custom-element.html:
<html>
<...>
<body>
<template id="myTemplate">
</template>
</body>
<script src="my-script.js">
</html>
my-script.js:
let customElementPrototype = Object.create(HTMLElement.prototype);
customElementPrototype.createdCallback = function () {
// somewhere here i want to access <template> to insert it in element
// I've tried document.querySelector("#myTemplate") and
// document.currentScript.ownerDocument.querySelector.querySelector("#myTemplate")
// they don't work either, result of querySelector is null
}
document.registerElement("custom-element", customElementPrototype);
用法:
<html>
<head>
<link rel="import" href="custom-element.html">
</head>
<...>
在createdCallback
上下文内部是custom-element
而不是。ownerDocument.
您可以console.log(this);
在createdCallback
which日志中看到此内容(来自我的plunker示例):
<div is="custom-element">
</div>
在中,my-script.js
您可以捕获对的引用,ownerDocument
并在回调中使用它。这将允许您的自定义元素访问其自身的DOM和导入的HTML的DOM。例如
var mainDoc = document.currentScript.ownerDocument;
完整my-script.js
(script.js
在我的朋克中):
var mainDoc = document.currentScript.ownerDocument;
var CustomElementPrototype = Object.create(HTMLElement.prototype);
CustomElementPrototype.createdCallback = function () {
console.log(this); //the div
//import the contents of the template
var clone = document.importNode(mainDoc.querySelector('#myTemplate').content, true);
//append template to div
this.appendChild(clone);
};
document.registerElement("custom-element", {
prototype: CustomElementPrototype,
extends: 'div'
});
结合具有默认值的模板(此文档可通过访问mainDoc
):
<html>
<body>
<script src="script.js"></script>
<template id="myTemplate">
hello world
<br>
from template
</template>
</body>
</html>
并将其全部使用的HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="import" href="custom-element.html">
</head>
<body>
<h1>Hello Plunker!</h1>
<div is="custom-element"></div>
</body>
</html>
https://plnkr.co/edit/jO3ci8vLxolHhvtGxJQ5
这是一个有用的参考:http : //webcomponents.org/articles/introduction-to-html-imports/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句