admin管理员组

文章数量:1310081

In each div, there are two buttons: higher and lower. When 'higher' is clicked, if this div is not at the top position, then it is moved higher than original. When 'lower' is clicked, then the element will be moved lower than original.

The question is: How to the elements can be moved up and down of with respect to another element?

<div>
    <div id="a1">a1<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
    <div id="a2">a2<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
    <div id="a3">a3<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
</div>

In each div, there are two buttons: higher and lower. When 'higher' is clicked, if this div is not at the top position, then it is moved higher than original. When 'lower' is clicked, then the element will be moved lower than original.

The question is: How to the elements can be moved up and down of with respect to another element?

<div>
    <div id="a1">a1<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
    <div id="a2">a2<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
    <div id="a3">a3<input name='higher' type='button' value='higher'/><input name='lower' type='button' value='lower'/></div>
</div>
Share Improve this question edited Jul 13, 2012 at 11:59 Ravindra S 6,44212 gold badges73 silver badges111 bronze badges asked Nov 7, 2010 at 6:57 mlzboymlzboy 14.7k23 gold badges80 silver badges98 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can try something like this: http://www.jsfiddle/yijiang/hwPPP/

With insertAfter and insertBefore we can move the parent of the buttons up and down.

$('#list').delegate('input[type="button"]', 'click', function() {
    var parent = $(this).parent();

    if(this.value === 'higher'){
        parent.insertBefore(parent.prev());
    } else {
        parent.insertAfter(parent.next());
    }

    return false;
});

Maybe you should look into something like JqueryUI Sortable:

http://jqueryui./demos/sortable/

Otherwise you could use next()/previous() and insertBefore()/insertAfter() jquery functions together:

$("#a1").insertAfter($('#a1').next());

本文标签: javascriptjQuery Move element positionStack Overflow