它在元素(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/