Html5拖放svg元素

我想在这里按照html5拖放教程。 我无法在rect元素上注册dragstart事件。 如果我将事件从draggable更改为mousedown则调用handleDragStart处理程序。 请忽略代码中的其他空白注册。

JSFiddle 在这里


     svg rect { cursor: move; }   

SVG/HTML 5 Example

loc.js

 $(document).ready(function() { function handleDragStart(e) { log("handleDragStart"); this.style.opacity = '0.4'; // this ==> e.target is the source node. }; var registercb = function () { $("#cvs > rect").each(function() { $(this).attr('draggable', 'true'); }); $("#cvs > rect").bind('dragstart', handleDragStart); $(window).mousedown(function (e) { }); $(window).mousemove(function (e) { }); $(window).mouseup(function (e) { log("mouseup"); }); }; function log() { if (window.console && window.console.log) window.console.log('[XXX] ' + Array.prototype.join.call(arguments, ' ')); }; registercb(); }); 

我知道这是一个老问题,我从这个被标记为这个问题的副本的问题到达这里,并希望添加一个不需要jQuery或任何库的可能解决方案,并且适用于所有主流浏览器。 它基于@AmirHossein Mehrvarzi推荐的本教程 。

这个小解决方案不使用拖动事件,只使用mousedownmouseupmousemove 。 这是它的工作原理:

  • 当鼠标在矩形上向下时,它会保存鼠标位置和活动元素。
  • 当鼠标移动时,矩形坐标将使用新的鼠标位置进行更新。
  • 当鼠标向上时,它会重置活动元素。

从上面问题中的代码:

 var selectedElement = null; var currentX = 0; var currentY = 0; $(document).ready(function() { function handleDragStart(e) { log("handleDragStart"); this.style.opacity = '0.4'; // this ==> e.target is the source node. }; var registercb = function () { $("#cvs > rect").mousedown(function (e) { // save the original values when the user clicks on the element currentX = e.clientX; currentY = e.clientY; selectedElement = e.target; }).mousemove(function (e) { // if there is an active element, move it around by updating its coordinates if (selectedElement) { var dx = parseInt(selectedElement.getAttribute("x")) + e.clientX - currentX; var dy = parseInt(selectedElement.getAttribute("y")) + e.clientY - currentY; currentX = e.clientX; currentY = e.clientY; selectedElement.setAttribute("x", dx); selectedElement.setAttribute("y", dy); } }).mouseup(function (e) { // deactivate element when the mouse is up selectedElement = null; }); }; function log() { if (window.console && window.console.log) window.console.log('[XXX] ' + Array.prototype.join.call(arguments, ' ')); }; registercb(); }); 
 rect { cursor: move; } 
  

SVG/HTML 5 Example

此行为可能由以下几个原因引起:

  • 根据这篇文章 ,HTML 5拖放是一团糟。 我知道它有点老了,但这个问题似乎还没有解决
  • jQuery不支持SVG DOM模型。 因此,它的某些部分可能有效,而有些部分则无效(如offset()width() )。

我现在绝对不依赖于HTML5拖放支持,而是使用库来处理这个问题。 如果你想使用SVG,你可以尝试Raphaël 。 如果你也需要jQuery,也许SVG插件是可行的方法。 请注意,目前这两个项目都没有积极开发。 我知道这不是一个令人满意的答案,但我也必须学习,jQuery和SVG并不能很好地结合在一起。 希望有人certificate我错了;)。