gpt4 book ai didi

jquery append 不适用于 svg 元素?

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:44 25 4
gpt4 key购买 nike

假设这样:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
});
</script>
</head>
<body>
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px">
</svg>
</body>

为什么我什么都没看到?

最佳答案

当您将标记字符串传递到 $ 时,使用浏览器的 innerHTML 将其解析为 HTML <div> 上的属性(property)(或其他适合特殊情况的容器,如 <tr> )。 innerHTML无法解析 SVG 或其他非 HTML 内容,即使可以解析也无法判断 <circle>应该在 SVG 命名空间中。

innerHTML在 SVGElement 上不可用——它只是 HTMLElement 的一个属性。目前也没有 innerSVG属性或其他方式 (*) 将内容解析为 SVGElement。因此,您应该使用 DOM 样式的方法。 jQuery 不会让您轻松访问创建 SVG 元素所需的命名空间方法。实际上,jQuery 根本不是为与 SVG 一起使用而设计的,许多操作可能会失败。

HTML5 promise 让你使用 <svg>没有 xmlns将来在纯 HTML ( text/html) 文档中。但这只是一个解析器 hack(**),SVG 内容仍然是 SVG 命名空间中的 SVGElements,而不是 HTMLElements,因此您将无法使用 innerHTML尽管它们看起来像 HTML 文档的一部分。

但是,对于当今的浏览器,您必须使用 XHTML(正确地用作 application/xhtml+xml ;使用 .xhtml 文件扩展名保存以进行本地测试)才能使 SVG 正常工作。 (无论如何,这有点有意义;SVG 是一个适当的基于 XML 的标准。)这意味着您必须转义 <脚本 block 中的符号(或包含在 CDATA 部分中),并包含 XHTML xmlns声明。示例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
<svg id="s" xmlns="http://www.w3.org/2000/svg"/>
<script type="text/javascript">
function makeSVG(tag, attrs) {
var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}

var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
document.getElementById('s').appendChild(circle);
circle.onmousedown= function() {
alert('hello');
};
</script>
</body></html>

*:嗯,有 DOM Level 3 LS 的 parseWithContext , 但浏览器支持很差。编辑添加:但是,虽然您不能将标记注入(inject)到 SVGElement 中,但您可以使用 innerHTML 将新的 SVGElement 注入(inject)到 HTMLElement 中。 ,然后将其转移到所需的目标。不过它可能会慢一点:

<script type="text/javascript"><![CDATA[
function parseSVG(s) {
var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
var frag= document.createDocumentFragment();
while (div.firstChild.firstChild)
frag.appendChild(div.firstChild.firstChild);
return frag;
}

document.getElementById('s').appendChild(parseSVG(
'<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
));
]]></script>

**:我讨厌 HTML5 的作者似乎害怕 XML,并决心将基于 XML 的特性硬塞进 HTML 的困惑局面。 XHTML 多年前就解决了这些问题。

关于jquery append 不适用于 svg 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32644848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com