JS offsetX和offsetY在新位置和原始位置之间闪烁

时间:2015-08-21 05:14:25

标签: javascript html5

我正在寻找的理想结果是红色方块平滑地跟随鼠标,而不是闪烁回原始位置。基本上,我想单击红色方块,将其拖动到某个区域,然后释放以使其成为新位置。它为什么会闪烁,我怎样才能实现简单的拖动和跟随?

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/

1 个答案:

答案 0 :(得分:0)

我刚刚更改了您的javascript代码,可能对您有所帮助,请检查此....

&#13;
&#13;
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;
&#13;
<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>
&#13;
&#13;
&#13;