【发布时间】:2016-11-25 18:00:00
【问题描述】:
我一直在试验 HTML5 和 SVG;而且我对 JavaScript 和 Web 开发非常陌生,所以我可能缺少一些东西。我正在尝试创建可重用的 Web 组件,利用一些新功能,例如 HTML 导入、Shadow DOM,并扩展现有的 Web 元素。我有两个 html 文件:
test.html
<html>
<head>
<title>Test HTML5</title>
</head>
<body>
<link rel="import" href="Elements/tank.html">
<svg width="100%"
viewBox="0 0 500 500"
style="border: solid; border-width: thin; stroke-width: 2;">
<polyline points="0,300 100,300 100,100 250,100 250,150 500,150"
style="fill:none;stroke:black;stroke-width:3"
onclick="window.alert('you clicked line')" />
<svg is="my-tank" x="200" y="350" width="50" height="50"></svg>
</svg>
</body>
</html>
tank.html
<html>
<body>
<template id="tank">
<rect fill="red" width="50" height="50"></rect>
</template>
<script type="text/javascript">
var tankElement = document.currentScript.ownerDocument.querySelector('#tank');
document.registerElement('my-tank', {
prototype: Object.create(SVGSVGElement.prototype, {
createdCallback: {
value: function () {
var root = this.createShadowRoot();
//Works
root.innerHTML = tankElement.innerHTML;
//Doesn't work
//var tankTemplate = document.importNode(tankElement.content, true);
//root.appendChild(tankTemplate);
}
}
}),
extends: 'svg'
});
</script>
</body>
</html>
//Works 注释下的代码在 SVG 可绘制空间中绘制了一个红色矩形。 //Doesn't work 下的代码没有绘制任何东西或产生任何错误。
//Works:的截图
//Doesn't work:的截图
我一直在使用 Opera 41.0 进行测试。
【问题讨论】:
标签: javascript html svg web-component shadow-dom