2015-08-22 91 views
1

我正在学习飞镖,我试图制作一个非常简单的可拖拽HTML元素。我遵循JavaScript习惯的模式,但不能按预期工作。飞镖中的愚蠢的鼠标移动坐标

当从头开始制作drageable对象,你通常会做以下操作:

  1. 侦听鼠标按下事件对象
  2. 在鼠标就下来了,记得鼠标坐标相对于对象的左上角
  3. 收听任何鼠标移动。对于每个移动操作,将对象移动到光标位置减去您先前记住的坐标。
  4. 任何鼠标移动事件发生后,请停止鼠标移动。

所以我制作这段代码:

class DrageableControl { 
    DivElement _elm; 
    DrageableControl(String txt, int x, int y) { 
    //Create element and set up styles 
    var elm = this.setupElement(x, y); 
    //Append element to document, add some text and start listeners 
    document.body.append(elm); 
    elm.text = txt; 
    setupEvents(); 
    } 
    //This function creates all event necessary for drag operations 
    setupEvents() { 
    Point relativeMouseOffset = null; 
    _elm.onMouseDown.listen((MouseEvent e) { 
     Rectangle myPos = _elm.getBoundingClientRect(); 
     relativeMouseOffset = new Point(e.offset.x-myPos.left, e.offset.y-myPos.top); 
     e.preventDefault(); 
     return false; 
    }); 
    //Of course this is completely wrong, the listener should only be added for the duration of dragging 
    document.onMouseMove.listen((MouseEvent e) { 
     if(relativeMouseOffset!=null) { 
     print("Clicked at: ${relativeMouseOffset}\nCurrent mouse position:${e.offset}"); 
     _elm.style.top = "${(e.offset.y/*-relativeMouseOffset.y*/)}px"; 
     _elm.style.left = "${(e.offset.x/*-relativeMouseOffset.x*/)}px"; 
     } 
    }); 

    document.onMouseUp.listen((MouseEvent e){ 
     relativeMouseOffset = null; 
    }); 
    } 



    setupElement(int x, int y) { 

    var elm = this._elm = new DivElement(); 
    //TODO: Use css? 
    elm.style.position = "absolute"; 
    elm.style.top = "${y}px"; 
    elm.style.left = "${x}px"; 
    elm.style.border = "1px solid red"; 
    elm.style.backgroundColor = "#FFAAAA"; 
    elm.style.cursor = "default"; 
    //elm.style.transition = "top 1s"; 
    return elm; 
    } 
} 

的问题是,通过MouseMove带来了一些坐标是完全荒谬的。看到控制台:

Clicked at: Point(-76.0, -143.0) 
Current mouse position:Point(1, 1) 
Clicked at: Point(-76.0, -143.0) 
Current mouse position:Point(374, 272) 
Clicked at: Point(-76.0, -143.0) 
Current mouse position:Point(1, 0) 
Clicked at: Point(-76.0, -143.0) 
Current mouse position:Point(376, 273) 
Clicked at: Point(-76.0, -143.0) 
Current mouse position:Point(0, 1) 

正如你可以看到每一个第二鼠标移动事件提供断线的数据 - 坐标对周围[0, 0]。那么如何过滤出这些无效的数据呢?为什么会发生?

到目前为止,我可能通过增加固定的:

if(e.offset.x+e.offset.y<5) 
    return; 
+1

这是一段时间,因为我实现了拖N - 下降,但我没有用偏移AFAIR。您是否尝试了'e.client.x' /'e.client.y'。 –

+0

是的,就是这样。问题是由于'MouseMove'事件也会冒泡并且'offset'属性保存相对于触发事件的元素的坐标而引起的。这就是我得到那些奇怪数字的原因。 –

回答

1

使用e.client.x/e.client.y代替。