Javascript jQuery 将 div 从位置 1 移动到 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11880012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:31:20  来源:igfitidea点击:

jQuery move div from position 1 to 2

javascriptjquery

提问by user1355300

I have multiple divs (haveing same class names). I want to move the div (always same div, which has unique ID #pos1) to the div which has been clicked. So, for that purpose, I am using following code to find the position1 (of the div which I want to move) and pos2 (the div which is clicked).

我有多个 div(具有相同的类名)。我想将 div(始终是相同的 div,具有唯一 ID #pos1)移动到已单击的 div。因此,为此,我使用以下代码来查找 position1(我想要移动的 div)和 pos2(单击的 div)。

However, I don't know know how can I move (animate etc) the div from one position to another. I will appriciate any help.

但是,我不知道如何将 div 从一个位置移动(动画等)到另一个位置。我会感谢任何帮助。

jQuery(".container").click(function() {

    var pos1 = jQuery("#pos1").position();
    alert(pos1.top + ', ' + pos1.left);

    var pos2 = jQuery(this).position();
    alert(pos2.top + ', ' + pos2.left);

});

采纳答案by udidu

First of all make sure that all your .containerdivs are position:absolute

首先确保你所有的.containerdiv 都是position:absolute

Then you can use the following animatefunction of jQuery:

然后你可以使用animatejQuery的以下功能:

$('.container').click(function(){
    var pos1 = $('#pos1').position();

    $(this).animate({ 'top': pos1.top + 'px', 'left': pos1.left + 'px'}, 200, function(){
        //end of animation.. if you want to add some code here
    });
});

回答by Ankur

Both the divs should have position :relativeor may be you can give your moving div a position: absolutefor top and left to work properly.

两个 div 都应该有position :relative或者可能是你可以给你的移动 div a position: absolutefor top 和 left 以正常工作。