I have an SVG rect element that I need to drag around the screen. The problem is that it doesn't work when dragging fast. I posted the code in jsFiddle.

The example in this post solves the problem in JQuery. I adapted the solution to SVG but it doesn't work. Any ideas?

This is the HTML code:

<svg id="svg" width="800" height="800" style="border: 1px dashed black;"
onmousemove="move(evt)" onmouseup="endMove(evt)" onmouseout="endMove(evt)">

<rect id="r" x="100" y="100" height="150" width="150" onmousedown="mouseDown(evt)"/>

</svg>

And the javascript:

  var click=false; // flag to indicate when shape has been clicked
  var clickX, clickY; // stores cursor location upon first click
  var moveX=0, moveY=0; // keeps track of overall transformation
  var lastMoveX=0, lastMoveY=0; // stores previous transformation (move)


function mouseDown(evt){
    evt.preventDefault();
    click=true;
    clickX = evt.clientX; 
    clickY = evt.clientY;
}

function move(evt){
evt.preventDefault();
if(click){
    moveX = lastMoveX + ( evt.clientX - clickX );
    moveY = lastMoveY + ( evt.clientY - clickY );
    evt.target.setAttribute("transform", "translate(" + moveX + "," + moveY + ")");
  }
}

function endMove(evt){
    click=false;
    lastMoveX = moveX;
    lastMoveY = moveY;
}
有帮助吗?

解决方案

As others have mentioned, you'll need to look into your endMove handler and clean up the logic there.

However, simply removing the handler isn't quite the answer (since you'll find yourself with a "jerky" experience if you continue mousing around).

Here are two things I would recommend (with a fiddle: http://jsfiddle.net/uUbRy/)

Capture the element that has focus.

In mouseDown, I set elementWithFocus = evt.target to use in your mousemove handler.

Address the endMove issue.

For that, I've updated your handler with the following condition check:

if(evt.type == 'mouseout' && click) {
    return;
}

其他提示

The problem is that when you move your mouse quickly, the cursor can end up temporarily outside of the box, before it catches up with the position. This causes an onmouseout event to be fired, which stops the dragging. To fix this you can simply remove the attribute onmouseout="endMove(evt)" from your svg object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top