我一直在试验 HTML5 和 SVG;而且我对 JavaScript 和 Web 开发还很陌生,所以我可能缺少一些东西。我正在尝试创建可重用的 Web 组件,利用一些新功能,例如 HTML 导入、Shadow DOM 和扩展现有的 Web 元素。我有两个 html 文件:
测试.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>
坦克.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
截图:
的屏幕截图//不起作用
:
我一直在使用 Opera 41.0 进行测试。
最佳答案
你不能这样做,因为svg
不能是影子主机。只有有限数量的元素可以成为影子宿主:
article
, aside
, blockquote
, body
, div
, footer
, h1
, h2
, h3
, h4
, h5
, h6
, header
, main
, nav
, p
, section
, span
.
所以不仅svg
, 还有其他人喜欢 input
或 textarea
不能有 shadow-dom(我说的是 Shadow-DOM v1)。
参见 attachShadow
的定义详情:https://dom.spec.whatwg.org/#dom-element-attachshadow
另请注意:
-
SVGSVGElement
不执行HTMLElement
. - 还听说 SVG 在其实现中已经包含了 shadow-dom,并且带有自定义元素 v1 你可能只有一个 shadow-dom(见这里:http://hayato.io/2016/shadowdomv1/)。
为什么不创建一个常规的自定义元素,它可能包含 <svg>
其影子域内的元素?
关于javascript - 使用 Shadow DOM 增强 SVG 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40810372/