2015-08-22 31 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代替。