Jquery动画移动元素左不工作

Jquery animate move element left not working at all

本文关键字:工作 元素 动画 移动 Jquery      更新时间:2023-09-26

我正在做一款可以拖动元素的游戏当拖动时元素必须移动

左(加减)取决于拖动方向。我已经试过无数种方法了。正常的'revert:true'对于水平元素不能正常工作,因为元素

返回到错误的位置。最后,我使用了Jquery中的animate()函数,它确实有效

可以,但是它只能上下拖动元素,但是左右方向不能

工作。下面是我的js脚本:

function setAllMatchesDraggable(){
    $('.matches').not('.answer').draggable({
        // Can't use revert, as we animate the original object
        //revert: true,
        helper: function(){
            // Create an invisible div as the helper. It will move and
            // follow the cursor as usual.
            return $('<div></div>').css('opacity',0);
        },
        create: function(){
            // When the draggable is created, save its starting
            // position into a data attribute, so we know where we
            // need to revert to.
            var $this = $(this);
            if(($this).hasClass("flip_left") || ($this).hasClass("flip_right"))
            {
                $this.data('top',$this.position().top - 29);
                $this.data('left',$this.position().left);
            }else{
                $this.data('top',$this.position().top);
                $this.data('left',$this.position().left);
            }
        },
        stop: function(){
            // When dragging stops, revert the draggable to its
            // original starting position.
            var $this = $(this);
            $this.stop().animate({
                "top": $this.data('top')
            },200,'easeOutElastic',function(){
              $(this).stop().animate({"left":$this.data('left')},200,'easeOutElastic');
            });
        },
        drag: function(event, ui){
            // During dragging, animate the original object to
            // follow the invisible helper with custom easing.
            $(this).stop().animate({
                "top": ui.helper.position().top
            },200,'easeOutElastic',function(){

                     $(this).stop().animate({"left":ui.helper.position().left},200,'easeOutElastic',function(){
                    console.log(ui.helper.position().left);
                });
            });
        }
    });
}

我希望你能帮忙。提前感谢:)

在同一函数中使用top和left

            $this.stop().animate({
                "top": $this.data('top'), 
                "left" : $this.data('left')
            },200,'easeOutElastic') ;

试一试:

    ...
    create: function(){
        var $this = $(this);
        $this.data({
            'top': $this.position().top,
            'left': $this.position().left
        });
    },
    stop: function(){
        var $this = $(this);
        $this.stop().animate({
            top: $this.data('top'),
            left: $this.data('left')
        },200,'easeOutElastic');
    },
    drag: function(event, ui){
        $(this).stop().animate({
            top: ui.helper.position().top,
            left: ui.helper.position().left
        },0,'easeOutElastic');
    }
    ...