【问题标题】:SVG: Dragging a rect works only if dragging slowlySVG:拖动矩形仅在缓慢拖动时有效
【发布时间】:2014-06-25 05:27:59
【问题描述】:

我有一个 SVG 矩形元素,需要在屏幕上拖动。问题是快速拖动时它不起作用。我把代码贴在jsFiddle

this post 中的示例解决了 JQuery 中的问题。我将解决方案改编为 SVG,但它不起作用。有任何想法吗?

这是 HTML 代码:

<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>

还有 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;
}

【问题讨论】:

  • 你的小提琴在任何速度下都能正常工作,除非我将鼠标移出页面。由于您的代码没有考虑到这一点,因此拖动不会在 mousein 上恢复。
  • 同意迈克。我认为问题在于您的 mouseout 处理程序过早地调用 endMove。

标签: javascript svg


【解决方案1】:

正如其他人所提到的,您需要查看您的 endMove 处理程序并清理那里的逻辑。

然而,简单地移除处理程序并不是完全的答案(因为如果你继续徘徊,你会发现自己有一种“生涩”的体验)。

这里有两件事我会推荐(用小提琴:http://jsfiddle.net/uUbRy/

捕获具有焦点的元素。

mouseDown 中,我将elementWithFocus = evt.target 设置为在您的鼠标移动处理程序中使用。

解决 endMove 问题。

为此,我使用以下条件检查更新了您的处理程序:

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

【讨论】:

    【解决方案2】:

    问题在于,当您快速移动鼠标时,光标可能会在赶上该位置之前暂时离开该框。这会触发 onmouseout 事件,从而停止拖动。 要解决此问题,您只需从 svg 对象中删除属性 onmouseout="endMove(evt)"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      相关资源
      最近更新 更多