如何在追加到父节点后拖动克隆元素。我尝试过拖动方法,但它不起作用。我是d3 js的新手,并试图在小提琴上学习基础和例子。
演示:https://jsfiddle.net/pmczny6k/
代码:
<html>
<head>
<title>Editor</title>
<meta http-equiv="x-ua-compatible" content="ie=9"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function ()
{
var svgContainer = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);
var circle = svgContainer.append("circle")
.attr("cx", 30)
.attr("cy", 30)
.attr("r", 20);
var rectangle = svgContainer.append("rect")
.attr("x", 100)
.attr("y", 100)
.attr("width", 50)
.attr("height", 50);
//clonning
function move() {
d3.select(rectangle)
.attr('x', d3.event.x - parseInt(d3.select(this).attr("width")) / 2)
.attr('y', d3.event.y - parseInt(d3.select(this).attr("height")) / 2);
this.parentNode.appendChild(this);
}
;
d3.selectAll(".drg").style("fill", "red")
.call(
d3.behavior.drag()
.on('drag', move).origin(function () {
var t = d3.select(this);
return {x: t.attr("x"), y: t.attr("y")};
})
.on('dragend', function (d) {
var elem = d3.select(this);
elem.attr("x", elem.attr("initial-x"));
elem.attr("y", elem.attr("initial-y"));
console.log(elem.attr("x"));
var mouseCoordinates = d3.mouse(this);
if (mouseCoordinates[0] > 70) {
//Append new element
d3.select("svg").append("rect")
.classed("drg", true)
.attr("width", 50)
.attr("height", 50)
.attr("x", mouseCoordinates[0])
.attr("y", mouseCoordinates[1])
.style("fill", "green");
}
})
)
};
</script>
</head>
<body>
<svg width="1024" height="768" style="background-color: #204d74">
<!--<g>-->
<rect x="10" y="20" height="250" width="300" style="fill: #080808"></rect>
<rect class="drg" x="12" y="22" initial-x="12" initial-y="22" height="50" width="50" style="fill: #f0ad4e"></rect>
<!--</g>-->
<rect x="10" y="280" height="250" width="300" style="fill: #080808"></rect>
<rect class="drg" x="12" y="282" initial-x="12" initial-y="282" height="50" width="50" style="fill: #f0ad4e"></rect>
<rect x="320" y="20" height="510" width="690" style="fill: #080808"></rect>
</svg>
</body>
</html>
答案 0 :(得分:2)
添加另一个调用到新创建的 rect 对象:
.call(
d3.behavior.drag()
.on('drag', move).origin(function() {
var t = d3.select(this);
return {x: t.attr("x"), y: t.attr("y")};
}));
更新了fiddle。
您还有一些语法错误。请在更好的语法高亮工具上检查它们,因为小提琴并不是一个好方法。希望它现在按预期工作。