2015-08-21 138 views
0

我期待的結果是紅色方塊順利地跟隨鼠標,而不是閃爍回原始位置。基本上,我想單擊紅色方塊,將其拖動到某個區域,然後釋放以獲得新的位置。爲什麼它閃爍,我怎樣才能實現簡單的拖拽和跟隨?JS偏移量X和偏移量Y在新位置和原始位置之間閃爍

HTML

<div style="height:500px; width:500px; background-color:#ccc;"> 
<div id="custom-front" style="width:100%; height:100%;"> 
    <div id="custom-content" style="z-index:200; position:absolute; text-align:center; background-color:red; width:50px; height:50px;"> 
    </div> 
</div> 

JS

window.onload = addListeners(); 
function addListeners(){ 
document.getElementById('custom-content').addEventListener('mousedown', mouseDown, false); 
window.addEventListener('mouseup', mouseUp, false); 
} 
function mouseUp() 
{ 
window.removeEventListener('mousemove', divMove, true); 
} 
function mouseDown(e){ 
window.addEventListener('mousemove', divMove, true); 
} 
function divMove(e){ 
document.getElementById('custom-content').style.top = e.offsetY + 'px'; 
document.getElementById('custom-content').style.left = e.offsetX + 'px'; 
} 

https://jsfiddle.net/703kc43a/1/

回答

0

我剛剛更改了javascript代碼,可能是這個幫助你,看看這個....

interact('.draggable') 
 
    .draggable({ 
 
    // enable inertial throwing 
 
    inertia: true, 
 
    // keep the element within the area of it's parent 
 
    restrict: { 
 
     restriction: "parent", 
 
     endOnly: true, 
 
     elementRect: { top: 0, left: 0, bottom: 1, right: 1 } 
 
    }, 
 

 
    // call this function on every dragmove event 
 
    onmove: dragMoveListener, 
 
    // call this function on every dragend event 
 
    onend: function (event) { 
 
     var textEl = event.target.querySelector('p'); 
 

 
     textEl && (textEl.textContent = 
 
     'moved a distance of ' 
 
     + (Math.sqrt(event.dx * event.dx + 
 
        event.dy * event.dy)|0) + 'px'); 
 
    } 
 
    }); 
 

 
    function dragMoveListener (event) { 
 
    var target = event.target, 
 
     // keep the dragged position in the data-x/data-y attributes 
 
     x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx, 
 
     y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy; 
 

 
    // translate the element 
 
    target.style.webkitTransform = 
 
    target.style.transform = 
 
     'translate(' + x + 'px, ' + y + 'px)'; 
 

 
    // update the posiion attributes 
 
    target.setAttribute('data-x', x); 
 
    target.setAttribute('data-y', y); 
 
    } 
 

 
    // this is used later in the resizing demo 
 
    window.dragMoveListener = dragMoveListener;
<script src="http://code.interactjs.io/interact-1.2.4.min.js"></script> 
 

 
<div style="height:500px; width:500px; background-color:#ccc;"> 
 
    <div id="custom-front" style="width:100%; height:100%;"> 
 
     <div id="custom-content" class="draggable" style="z-index:5; position:absolute; text-align:center; background-color:red; width:50px; height:50px;"> 
 
     </div> 
 
    </div> 
 
</div>