2010-11-07 237 views
3

在每個div中,有兩個按鈕:更高和更低。當點擊「更高」時,如果這個div不在最高位置,那麼它會比原來高。點擊「下面」時,元素將會移動到比原來更低的位置。jQuery:移動元素位置

問題是:如何將元素相對於另一個元素上下移動?

<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> 

回答

6

你可以嘗試這樣的事情:http://www.jsfiddle.net/yijiang/hwPPP/

隨着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; 
}); 
+0

這個jsfiddle.net網站真的很酷 – mlzboy 2010-11-07 07:28:36

1

也許你應該考慮像jQueryUI的可排序:

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

否則,你可以使用下一個()/上一個()和的insertBefore()/ insertAfter()jQuery的功能整合在一起:

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

g雖然這實現了我的要求,但我需要在我的項目中添加一個插件,我還是想找到一些手動的方式來實現這一 – mlzboy 2010-11-07 07:18:00

+0

這只是你如何使用功能的例子...的回答上面是一個很好的回答您的請求 – 2010-11-07 08:20:39