【问题标题】:SVG not showing up when added to HTML [duplicate]添加到 HTML 时未显示 SVG [重复]
【发布时间】:2012-11-21 09:37:50
【问题描述】:

我遇到了一个非常有趣的问题,当我将新的 SVG 元素添加到 div 时,只有第一次调用 append 时才会出现新的 svg 元素。它们在硬编码时工作,但是当它们被添加到 onmousedown 时,它们不会出现,即使它们被添加到 HTML 文件中。我假设这是我对SVG的理解有问题,并且无法动态添加元素,但是我一直在互联网上寻找,找不到任何关于该主题的内容。

您可以看到在 $(document).mousedown 函数中,一个新的圆圈被附加到了 svg holder 上,但是即使它被添加到 SVG holder 中,它也不会显示在网页上。

代码:

HTML:

<div id="svgHolder">
    <!--THIS CIRCLE SHOWS UP-->
    <svg><circle cx='50' cy='50' r='40' stroke='black' stroke-width='1' fill='red' /></svg>
</div>

JQuery/JavaScript:

$(document).ready(function(){

var mouse={
    x:0,
    y:0,
    drawing:false,
    lastX:0,
    lastY:0,

}

$(document).mousedown(function(e){
    console.log('md')
    mouse.x=e.clientX
    mouse.y=e.clientY
    mouse.drawing=true
            //THIS CIRCLE WILL BE ADDED TO THE SVGHOLDER, BUT WILL NOT SHOW UP
    $("#svgHolder").append("<svg><circle cx='"+mouse.x+"' cy='"+mouse.y+"' r='40' stroke='black' stroke-width='1' fill='red' /></svg>");
});

$(document).mouseup(function(e){
    console.log('mu')
    mouse.x=e.clientX
    mouse.y=e.clientY
    mouse.drawing=false
});



$(document).mousemove(function(e){
    console.log('mm')
    mouse.x=e.clientX
    mouse.y=e.clientY
});



});

【问题讨论】:

  • 也许尝试将命名空间添加到svg 标记。像这样..$("#svgHolder").append('&lt;svg xmlns="http://www.w3.org/2000/svg"&gt;&lt;circle cx= ...

标签: jquery html svg


【解决方案1】:

您的svg 正在插入,但在您的视口之外,因此您看不到它,将一些widthheight 添加到svg 并为cx 和@987654329 设置适当的值@属性,即

$(document).mousedown(function(e){
    $("#svgHolder")
    .append("<svg width='100' height='100'><circle cx='50' cy='50' r='40' stroke='black' stroke-width='1' fill='red' /></svg>");
});

还要记住 clientXclientY 以 CSS 像素为单位提供相对于视口的坐标。

Example1Example2more about SVG

【讨论】:

  • +1 - 在 svg 上设置显式宽度/高度或调整容器 div 的大小。
【解决方案2】:

我认为当您动态创建svg 节点时,您必须创建命名空间。

var ns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(ns, "svg");
$(svg).append("<circle ...");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2021-04-08
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多