直观地在DOM上交换两个HTML元素,并对其进行动画处理?

问题描述:

在jQuery中是否可以交换两个容器的位置-在视觉上和在DOM中,还可以对结果进行动画处理?

Is it possible in jQuery to swap the position of two containers - both visually and and in the DOM, but also animate the result?

我有:

<div id="container">
    <div id="one"><a class="moveUp">Up</a></div>
    <div id="two"><a class="moveUp">Up</a></div>
    <div id="three"><a class="moveUp">Up</a></div>
</div>

点击链接会将该div的位置与上面的位置交换. 大多数示例使用绝对定位并偏移top属性来实现此目的...但是我需要在用户在其他地方调用函数时,按数据在屏幕上显示的顺序读取数据.

Clicking the link will swap that div's position with the one above. Most examples use absolute positioning and offsets the top property to achieve this... but I need to read the data in the order it is displayed on screen when the user calls a function somewhere else.

所以我想到了这个:

$('#container div').on('click', '.moveUp', function() {

    divInQuestion = $(this).closest('div').attr('id');  //id of this div

    if (divInQuestion > '1') {

        switchWithDiv = divInQuestion - 1;  //id of other div

        firstSelector = $('#chapterset-'+divInQuestion).html();     //save contents of each div.  I actually don't 
        secondSelector = $('#chapterset-'+switchWithDiv).html();        //do it this way, I regenerate the content

        $('#chapterset-'+divInQuestion).html()firstSelector.replaceWith(secondSelector);    //replace div with other div
        $('#chapterset-'+switchWithDiv).html()secondSelector.replaceWith(firstSelector);
    }
});

现在,我的代码实际上比这还要复杂,但是它提供了我正在做的事情的外壳.

Now, my code is actually more complex than this, but it gives the shell of what I'm doing.

jQuery可以正常工作,但是我该如何添加动画?

jQuery works fine but, how would I include an animation?

PS:试图让jsFiddle运行,但是它们的服务器可能处于atm状态?!??

PS: Tried to get a jsFiddle going but their servers might be down atm??!!?

尝试先对其进行动画处理,以进行视觉交换,然后在以下位置将其交换到DOM中:

Try animating it first, to make the visual swap, and then swap them in the DOM after:

http://jsfiddle.net/BYossarian/GUsYQ/5/

HTML:

<div id="container">
    <div id="one"><a class="moveUp">Up 1</a></div>
    <div id="two"><a class="moveUp">Up 2</a></div>
    <div id="three"><a class="moveUp">Up 3</a></div>
</div>

CSS:

#container {
    width: 200px;
    border: 1px solid black;
    position: relative;
}
#container div {
    border: 1px solid black;
    position: relative;
}
#container a {
    display: block;
}

JS:

var animating = false;

$('#container').on('click', '.moveUp', function () {

    if (animating) {return;}

    var clickedDiv = $(this).closest('div'),
        prevDiv = clickedDiv.prev(),
        distance = clickedDiv.outerHeight();

    if (prevDiv.length) {
        animating = true;
        $.when(clickedDiv.animate({
            top: -distance
        }, 600),
        prevDiv.animate({
            top: distance
        }, 600)).done(function () {
            prevDiv.css('top', '0px');
            clickedDiv.css('top', '0px');
            clickedDiv.insertBefore(prevDiv);
            animating = false;
        });
    }
});