如何在点击时修复此div的偏移x位置?

时间:2015-04-09 19:30:31

标签: javascript draggable drag

使用vanilla JavaScript处理面板拖动功能。

现在停留在如何正确偏移拖拉机div的x位置,以便它不会捕捉到光标的右侧。

如何更正下面的x偏移?

enter image description here

http://jsfiddle.net/leongaban/rrcL63y9/41/

window.onload = addListeners();

var xPosition = 0;

function addListeners() {
    document.getElementById('drag-container').addEventListener("click", getClickPosition, false);

    document.getElementById('dragger').addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function getClickPosition(e) {
    xPosition = e.clientX;
    console.log(xPosition);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e) {
  window.addEventListener('mousemove', divMove, true);
}

function divMove(e) {
    var max = 443;
    var x = event.clientX;

    if (x > 100 && x < max) {
        var div = document.getElementById('dragger');
        div.style.position = 'absolute';

        div.x = xPosition;

        div.style.left = e.clientX + 'px';
    }

    //console.log(x);
}

1 个答案:

答案 0 :(得分:2)

您可以通过了解可拖动元素的宽度并将偏移调整为 - (width / 2)来实现;

function divMove(e) {
    var max = 443;
    var x = event.clientX;
    var div = document.getElementById('dragger');
    var offset = div.offsetWidth/2;

    if (x > (100 + offset) && x < (max+offset)) {

        div.style.position = 'absolute';

        div.x = xPosition;

        div.style.left = (e.clientX - offset) + 'px';
    }

    //console.log(x);
}

以下是更新后的fiddle