<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>d3</title> </head> <body> <div class="test"> </div> <script src="../js/jquery-2.1.4.js"></script> <script src="../js/d3.js"></script> <script> $(function(){ var dragmove = function(d){ d3.select(this) .attr({ cx: function(){ d.x = Math.max(20, Math.min(220, d3.event.x)); return d.x; }, cy: function(){ d.y = Math.max(20, Math.min(105, d3.event.y)); return d.y; } }) } var drag = d3.behavior.drag() .origin(function(d){ return d; }) .on('drag', dragmove); ; var svg = d3.select('.test') .selectAll('svg') .data([{ x: 120, y: 62 }]) .enter() .append('svg') .attr('width', 240) .attr('height', 125) ; svg.append('circle') .attr({ r: 20, cx: function(d) { return d.x; }, cy: function(d){ return d.y } }) .call(drag) ; }) </script> </body> </html>