2017-07-13 77 views
0

我目前正試圖創建我自己的拖放功能在JavaScript(與事件監聽),我面臨的一個問題:當我開始拖動我的元素,我無法瞭解因爲拖動的元素位於我的光標前面。獲取元素背後的另一個元素

我想知道是否有可能得到我的光標的位置,而不受元素即時拖動的影響。

注:我不能使用jQuery來達致這

感謝,

編輯:我的代碼

var i = 0; 
window.addEventListener('mousedown', startDrag); 
var leftMarg = document.getElementById('moving').offsetWidth/2; 
var topMarg = document.getElementById('moving').offsetHeight/2; 

function stopDrag(e) { 
    window.removeEventListener('mousemove', dragging); 
    window.removeEventListener('mouseup', stopDrag); 
    window.removeEventListener('mousemove', grabbing); 
} 

function startDrag() { 
    window.addEventListener('mouseup', stopDrag); 
    window.addEventListener('mousemove', grabbing); 
} 

function grabbing(e) { 
    for (let i = 1; i < document.getElementById("test").children.length; i++) { 
     if (document.getElementById("test").children[i].contains(e.target)) { 
      document.getElementById("moving").style.visibility = "visible"; 
      document.getElementById("moving").innerText = e.target.innerText; 
      window.removeEventListener('mousemove', grabbing); 
      window.addEventListener('mousemove', dragging); 
     } 
    } 
} 

function dragging(e) { 
    document.getElementById("moving").style.left = (e.x - leftMarg) + "px"; 
    document.getElementById("moving").style.top = (e.y - topMarg) + "px"; 
} 
+0

添加代碼,你爲它做 –

+0

歡迎[https://stackoverflow.com/](https://stackoverflow.com /) !在這個站點上,你應該嘗試自己編寫代碼。如果您遇到問題,在做了更多研究後,您可以發佈您已經嘗試過的內容,並清楚說明哪些內容無法正常工作並提供[最小,完整和可驗證的示例](https://stackoverflow.com/help/ mcve)。我建議閱讀[如何問](https://stackoverflow.com/help/how-to-ask)。祝你好運! – MorganFreeFarm

回答

0

聽的OnMouseMove事件中,你可以得到鼠標的位置時,與event.clientX/Y。例子在這裏:https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onmousemove(也含有拖放的例子),在這裏:https://jsfiddle.net/qf4atst5/

你需要計算clientX/Y - 元素的左/ topOffset獲得相對於你的元素:

鼠標位置

沒有jQuery的需要

PS:爲了讓您的鼠標位置刪除e.target.getBoundingClientRect().*

+0

謝謝,這是我所希望的最好的,我現在應該能夠做我想做的。 – Duncan