如何在另一个元素jquery的中心设置可拖动元素的动画

时间:2018-06-10 07:00:53

标签: jquery css

我想要将可拖动的div设置为另一个div的中心。我怎样才能做到这一点?实际上在这里我想将div.drag拖到div.fix的边缘,之后想要将元素转到div.fix的中心。谢谢你的帮助

sexbd: Female
            $(document).ready(function() {
                var widthFix = $(".fix").width() / 2;
                var HeightFix = $(".fix").height() / 2;
                var widthDrag = $(".drag").width() / 2;
                var HeightDrag = $(".drag").height() / 2;
                console.log(`x:${widthFix} y:${HeightFix}`);
    
                var distanceTop = $(".fix").offset().top;
                var distanceLeft = $(".fix").offset().left;
                console.log(distanceTop + " " + distanceLeft);
                $(".drag").mousedown(function() {
                    $(window).on("mousemove", function(e) {
                        var x = e.pageX;
                        var y = e.pageY;
                        $(".drag").css({
                            top: y,
                            left: x,
                            transform: "translate(-50%,-50%)"
                        });
    
                        if (x >= distanceLeft && y >= distanceTop) {
                            // alert("you loose");
    
                            $(".drag").animate({
    
                                left: HeightFix - HeightDrag,
                                top: widthFix - widthDrag,
    
                            }, 1000, "linear", function() {});
    
                        }
                    });

                $(".drag").mouseup(function() {


                    $(window).off("mousemove")

                });


            });

        });

1 个答案:

答案 0 :(得分:0)

您可以使用JQuery UI draggabledroppable并在drop事件上编写任务。

$('#drag').draggable();
$('#fix').droppable({
accept:'#drag',
drop:function(event,ui){
//now get the draggable element using ui object and set the style you want.
}
});