javascript - 无法将形状附加到 svg

标签 javascript d3.js svg

它在元素(png图像)上的dragstart事件上打印id,但是,形状没有在dragend事件上附加到svg。

window.onload = function ()
            {
                var svg = d3.select("body")
                        .append("svg")
                        .attr("width", 800)
                        .attr("height", 803);
            };
            var shapeId = "";

            function getId(id)
            {
                shapeId = id;
                console.log(shapeId);
            }

            function createShape()
            {
                if (shapeId == 'newTask')
                {
                    createRect();
                }
            }

            function createRect() 
            {
                console.log("createRect function called");
                svg.append("rect")
                        .attr("id", "onRectDragStart")
                        .attr("rx", 10)
                        .attr("width", 51)
                        .attr("height", 41)
                        .attr("x", "100")
                        .attr("y", "100")
                        .attr("stroke-width", 2)
                        .attr("stroke", "#7E7E7E")
                        .style('cursor', 'move')
                        .style("fill", "white")
                        .classed("initialDragRect", true);
            }

HTML:

<div id="content">
            <div style="position: relative; height: 100%;">
            <div><a id="newTask" title="Add new task" draggable="true" ondragstart=getId(this.id) ondragend="createShape(this)"><img src="task.png" /></a></div>
   </div>
    <div id="canvas" tabindex="0"></div>
</div>

createRect() 函数被调用作为其在控制台内的打印消息,但形状没有被附加

createShape(this) 在拖尾事件的 div 标签内被调用

最佳答案

您应该在 DOM 完全加载后加载脚本,因为您正在使用事件与 DOM 交互。

示例:

 <!DOCTYPE HTML>
    <html>

    <head>
      <!-- yada yada yada -->
    </head>

    <body>
      <p id='p1'>Line 1</p>
      <script type='text/javascript'>
        document.write("<p>p1 is null? " + (document.getElementById('p1') == null ? "yes" : "no") + "</p>");
        document.write("<p>p2 is null? " + (document.getElementById('p2') == null ? "yes" : "no") + "</p>");
      </script>
      <p id='p2'>Line two</p>
    </body>

    </html>

您看到的输出是:

Line 1
p1 is null? false
p2 is null? true
Line 2

因为 p1 在脚本运行时存在,但 p2 不存在。

检查这个link由谷歌开发人员提供更多信息。帮助这有帮助

关于javascript - 无法将形状附加到 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31961353/

相关文章:

javascript - 在页面加载时激活在线幻灯片放映

javascript - ReactJS,尝试从 JIRA 的 REST API 获取 JSON 数据,但无法这样做。

javascript - 如何使用 RequireJS 加载依赖于 d3 的脚本?

javascript - 垂直滚动条显示不正确

html - Icomoon selection.json,为现有项目添加新图标

javascript - xul: 在 xul 浏览器中打开一个相对于 "myapp.xul"的本地 html 文件

javascript - 在 Firefox 中显示小部件

javascript - 无法让4个圆圈同时出现

javascript - 创建面包屑路径

python beautifulsoup 给svg添加html标签