星期三, 4月 24, 2013

[jQuery plugin] 實作Shift + Click多選行為

如果要模擬window shift鍵多選的行為,可以參考以下這篇文章。
Snippet: Shift + Click List Items with jQuery
主要的邏輯是記錄最後一個選擇的項目
$parentNode.delegate("li","click",function(event){
    
    var $currLI = $(this);
   
    if($currLI.hasClass("select_this")){
     
     //unselected
     $.console("[UserList.render] delegate:unselected user");
     
     if(event.shiftKey){
      //just unselected
      $currLI.removeClass("select_this");
     }else{
      //re-locate last selected/unselected
      $currLI.removeClass("select_this");
      $currLI.addClass("last_selected");
      
      $lastSelected.removeClass("last_selected");
      
      //change last selected
      $lastSelected = $currLI;
     }
    }else{
     
     //selected 
     $.console("[UserList.render] delegate:selected user");
    
     //
     // SHIFT + CLICK
     //
     
     var $shiftSelected = [];//record seleted items by shfit key
     if(event.shiftKey){
      
      //shift + click logic 
      if($lastSelected.length > 0){//first click
       
       if($lastSelected == $currLI){
        $.console("[UserList.render] same selection");
        
        return false;
        
       }else{
        
        //detect foward or back
        direction = $currLI.nextAll(".last_selected").length > 0 ? "forward" : "back";
        $.console("[UserList.render] last_selected count:" + $currLI.nextAll(".last_selected").length);
        $.console("[UserList.render] direction:" + direction);
        
        if(direction == "forward"){
         $shiftSelected = $currLI.nextUntil($lastSelected);
        }else{
         //back
         $shiftSelected = $lastSelected.nextUntil($currLI);
        }
        
//        $.console("$shiftSelected:" + $shiftSelected.length);
        $LICollection.removeClass("select_this");//reset pre selected
        
        //final selected items
        $shiftSelected.addClass("select_this");//highlight shift selected
        $lastSelected.addClass("select_this");//highlight last selected
                 $currLI.addClass("select_this");//highlight current selected
                 
       }
       
      }else{
       
       $lastSelected = $currLI;
       $currLI.addClass("select_this last_selected");
      }
      
     }else{
      
      //record last selected
      $lastSelected = $currLI;
      $currLI.addClass("select_this last_selected");
  
     }
     
    }
    
    //for debug
//    $.console("lastselected username:" + $lastSelected.find(".usr_name").html());
    
    if(userlist.selecteEventHandler && typeof(userlist.selecteEventHandler) === "function"){
     userlist.selecteEventHandler($currLI,userlist.getSelectedItems());
    }
   });

沒有留言:

張貼留言

留個話吧:)