2010-05-12 72 views
1

我希望實現切換2個HTML分區被點擊時的位置的效果。開關元素位置通過JQUERY

所以點擊時,頂部會移到底部,底部會移到頂部。

這裏是我能想出

<html> 
<head> 
    <script type="text/javascript"> 
$(document).ready(
    function(){ 
     $('div').click(
      function(){ 
       $(this).insertBefore($(this).next()); 
      } 
     ); 
     } 
     ) 
    </script> 

    <style type="text/css"> 
    body{ 
    margin: 0; 
    } 
    #top{ 
height: 100px; 
width: 100px; 
background: rgb(206,206,203); 
    } 

    #bottom{ 
     height: 100px; 
     width: 100px; 
background: rgb(226,206,203); 
    } 
    </style> 

</head> 
<body> 
     <div id="top"></div> 
     <div id="bottom"></div> 
</body> 
</html> 

我知道有一種方法在jQuery選擇使用類,如下所示

<script type="text/javascript"> 
$(document).ready(
    function(){ 
     $('div').click(
      function(){ 
       **$('#bottom').insertBefore('#top');** 
      } 
     ); 
     } 
     ) 
    </script> 

選擇特定的元素,但我只想要一個通用的方式來移動具有任意名稱和類名稱的元素。

在此先感謝。

回答

1

我建議使用一類獨特的每一對相關聯,那麼你可以這樣做:

$('.pair').click(function() { 
    $('.pair:first').insertAfter($('.pair:not(:first)')); 
}); 
+0

感謝先生, 但BUG – 2010-05-12 20:02:17

+0

NVM固定謝謝 – 2010-05-12 20:03:09

+0

我還有個問題。這怎麼會永久影響Dom的佈局?這個開關可以永久保存在標記上嗎? – 2010-05-12 20:04:33