首页 文章

jQuery - 如何在拖动事件期间为可拖动div移动光标设置动画

提问于
浏览
1

我正在使用jquery UI draggable,并希望在拖动事件期间有一个可拖动的div动画 . 想象一下,当静止时,示例中的方形div附着在磁铁上 . 你点击它并开始拖动,它将不会拖动,直到达到一定的距离阈值(距离= div中心和当前鼠标位置之间的距离) . 达到该阈值后,div将为鼠标设置动画,然后应进入正常的拖动事件 .

我的问题是当鼠标以足够快的速度被拖过距离阈值时,div将开始闪烁,因为它在显示动画div和被拖动的div之间切换 . 出现的另一个问题是,如果你足够快地拖动鼠标然后停止,div会动画到最后记录的鼠标位置,但是在计算时,鼠标可能已经处于不同的位置,所以鼠标是在一个地方,div在另一个地方 . 关于如何使div动画鼠标然后在一个平滑过渡中继续拖动事件的任何想法? (另外,我希望动画足够长,以便你可以看到div移动 . 如果持续时间设置为1,它工作正常,但我希望它更具视觉吸引力和流畅)这是一个演示:http://jsfiddle.net/b84wn2nf/

以下是演示中的一些代码:

$(".dragSquare").draggable({
drag: function (event, ui) {

    if($(this).hasClass("stuck")){
    var mx = event.pageX;
    var my = event.pageY;
    ui.position.left = $(this).position().left;
    ui.position.top = $(this).position().top;

    var d = Math.floor(Math.sqrt(Math.pow(mx - ($(this).offset().left + ($(this).width() / 2)), 2) + Math.pow(my - ($(this).offset().top + ($(this).height() / 2)), 2)));
    console.log(d)
    if (d > 200) {
        var animateToX = event.pageX - $(this).width() / 2;
        var animateToY = event.pageY - $(this).height() / 2;

        $(this).stop(true, true).animate({
            left: animateToX + 'px',
            top: animateToY + 'px'
        }, {
            /*easing: 'easeOutBounce,'*/
            duration: 500,
            start: function () {},
            complete: function () {
                $(this).removeClass("stuck");
            }
        });
    }
    }
} });

1 回答

  • 0

    好吧,所以我知道我很久以前发布了这个,从那以后,我开始使用Snap.js SVG库而不是jQuery,这使得更容易取消拖动,但在切换之前,我解决了问题唯一的方法:通过修改源代码 .

    在jquery-ui.js中,找到jQuery UI Draggable部分,然后向下滚动到_mouseDrag方法 . 你需要在自己的代码中做什么设置一个全局变量来告诉jQuery你是否想要覆盖拖动行为 . 我使用'cancelDrag'作为变量名 . 因此,当它设置为false时,拖动行为正常 .

    在_mouseDrag中,您将看到以下代码:

    this.helper[0].style.left = this.position.left + "px";
    this.helper[0].style.top = this.position.top + "px";
    

    你需要做的是将它包装在一个取决于你的布尔变量的条件语句中,所以它看起来像这样:

    if(!cancelDrag){
        this.helper[0].style.left = this.position.left + "px";
        this.helper[0].style.top = this.position.top + "px";
    }
    

    基本上,如果cancelDrag设置为true,则jQuery拖动处理程序不会更改元素的位置 . 它不理想,应该不应该使用,但它的工作原理 . 确保如果修改此文件,则不使用缩小的源 .

相关问题