简体   繁体   English

jQuery:移动元素位置

[英]jQuery: Move element position

In each div, there are two buttons: higher and lower. 在每个div中,有两个按钮:更高和更低。 When 'higher' is clicked, if this div is not at the top position, then it is moved higher than original. 单击“更高”时,如果此div不在顶部位置,则将其移动到高于原始位置。 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>

You can try something like this: http://www.jsfiddle.net/yijiang/hwPPP/ 你可以试试这样的东西: http//www.jsfiddle.net/yijiang/hwPPP/

With insertAfter and insertBefore we can move the parent of the buttons up and down. 使用insertAfterinsertBefore我们可以上下移动按钮的父级。

$('#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: 也许你应该看看像JqueryUI Sortable这样的东西:

http://jqueryui.com/demos/sortable/ http://jqueryui.com/demos/sortable/

Otherwise you could use next()/previous() and insertBefore()/insertAfter() jquery functions together: 否则你可以使用next()/ previous()和insertBefore()/ insertAfter()jquery函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM