修复JQuery拖动函数的偏移量

时间:2014-03-18 22:25:23

标签: jquery

小提琴 - http://jsfiddle.net/wLXsp/1/

我可以拖动一个div并让它移动得很顺畅,但是我遇到了这个烦人的偏移问题,我无法解决问题。

非常感谢任何帮助。

var onmove = false;

$('.rect').on('mousedown touchstart', function(e) {
    onmove = 1
});

$(document).on('mousemove touchmove', function(e) {
    if (onmove) {
        $('.rect').css({
            'top': e.pageY,
            'left': e.pageX
        });
    }
}).on('mouseup touchend', function() {
    onmove = false;
});

1 个答案:

答案 0 :(得分:1)

以下作品:

var onmove = false;
var x1;var y1;var x2;var y2;var x3; var y3;

$('.rect').on('mousedown touchstart', function(e) {
    onmove = 1;
    x1 = event.clientX;
    y1 = event.clientY;
    x3 = parseInt($('.rect').css('left'));
    y3 = parseInt($('.rect').css('top'));
});

$(document).on('mousemove touchmove', function(e) {
    if (onmove) {
            x2 = e.clientX;
            y2 = e.clientY;

            distX = x2 - x1;
            distY = y2 - y1;

            var newX = x3 + distX;
            var newY = y3 + distY;

            $('.rect').css('left', newX);
            $('.rect').css('top', newY);

    }
}).on('mouseup touchend', function() {
    onmove = false;
});