2011-06-11 41 views
5

我有一種情況,我想根據事件定位某些元素。例如:如何使用jQuery爲一個事件排序元素

<div id="leftBox"> 
    <div class="green">GREEN</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
</div> 



<div id="rightBox"> 
    <div class="green">GREEN</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
    <div class="green">GREEN</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
    <div class="green">GREEN</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
</div> 

當我鼠標移到#leftBox。綠色,我想在的#rightbox所有元素用。綠色在上面,如:

<div id="rightBox"> 
    <div class="green">GREEN</div> 
    <div class="green">GREEN</div> 
    <div class="green">GREEN</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
    <div class="blue">BLUE</div> 
    <div class="red">RED</div> 
</div> 

和喜歡同樣的爲的.blue.red

+0

我嘗試了一些。請檢查它,朋友。 – thecodeparadox 2011-06-11 06:23:08

+0

朋友,如果這個解決方案適合你,你應該把它當作答案。 – thecodeparadox 2011-06-11 06:44:28

回答

2
$(document).ready(function(){ 

    $("div#leftBox div").mouseover(function(){ 

     $("div#rightBox ."+$(this).attr('class')).each(function() { 

      $("div#rightBox").prepend($(this)); 
     }); 

    }); 

}); 

這也工作得很好,你可以查看這裏的演示,http://jsfiddle.net/S8TXq/

如果您想保留其他元素順序,只需試試這個

$(document).ready(function(){ 

    $("div#leftBox div").mouseover(function(){ 
     main = $('#rightBox div').clone(true); 
     $("div#rightBox ."+$(this).attr('class')).each(function() { 

      $("div#rightBox").prepend($(this)); 
     }); 

    }).mouseout(function() { 
    $('#rightBox').empty().append(main);}); 

}); 

http://jsfiddle.net/S8TXq/5/

1

試試這個:

var main, address; 
    $('#leftBox div').mouseenter(function() { 
     address = $(this).attr('class'); 
     var stack = [], 
     tmp = [], 
     total = []; 
     main = $('#rightBox div').clone(true); 
     stack = $('#rightBox div.'+ address +'').remove(); 
     tmp = $('#rightBox div'); 
     total = $.merge(stack, tmp); 
     $.each(total, 
     function() { 
      $(this).appendTo('#rightBox').show(); 
     }) 
    }).mouseout(function() { 
     $('#rightBox').empty().append(main);}); 
相關問題