2014-07-14 12 views
2

作爲一個小練習,我決定重新創建Windows 8資源管理器文件列表面板,並且一切順利,直到我想添加鼠標選擇。基本上,這個功能允許您通過沿着窗口拖動鼠標來選擇多個文件,繪製一個正方形,應該選擇所有屬於它的「文件」。創建Windows 8資源管理器模擬 - 鼠標選擇問題

我唯一的問題是,我似乎無法找到一種方法來selected類添加到元素的選擇下

下面是相關的代碼:(完整的代碼可以在working fiddle

<ul class="files"> 
    <li> 
     <span class="icon folder"></span> 
     <span class="name">Folder</span> 
    </li> 
</ul> 

.selection { 
    position: absolute; 
    border: 1px solid #39F; 
    background-color: rgba(51,153,255,.4); 
    display: none; 
} 

$(function(){ 
    var $body = $(document.body); 
    var selecting = false, 
     $selectionDiv = $(document.createElement('div')).addClass('selection').appendTo($body), 
     startX, startY; 
    $body.on({ 
     mousedown: function(e){ 
      if (e.target === document.body){ 
       e.stopPropagation(); 

       startX = e.clientX; 
       startY = e.clientY; 
       selecting = true; 

       $selectionDiv.show().css({top:startY+'px',left:startX+'px',width:'0px',height:'0px'}); 
      } 
     }, 
     mousemove: function(e){ 
      if (selecting){ 
       var currentX = e.clientX, 
        currentY = e.clientY; 

       var subX = currentX - startX, 
        subY = currentY - startY; 

       if (subX < 0){ 
        subX *= -1; 
        $selectionDiv.css('left',startX+(currentX-startX)); 
       } 
       else $selectionDiv.css('left',startX+'px'); 

       if (subY < 0){ 
        subY *= -1; 
        $selectionDiv.css('top',startY+(currentY-startY)); 
       } 
       else $selectionDiv.css('top',startY+'px'); 

       $selectionDiv.css({ 
        width: subX, 
        height: subY, 
       }); 
      } 
     } 
    }).on('mouseup blur mouseleave',function(){ 
     if (selecting){ 
      $selectionDiv.hide(); 
      selecting = false; 
     } 
    }); 
}); 

回答

4

如果我理解正確的話,你需要確定哪些元素包含在選擇框裏面。以下是這似乎做的工作代碼(它應該進入你的mousemove事件處理程序):

var topLeftX = Math.min(startX, currentX), 
    topLeftY = Math.min(startY, currentY), 
    bottomRightX = Math.max(startX, currentX), 
    bottomRightY = Math.max(startY, currentY); 

$('.files li').each(function() { 
    var offset = $(this).offset(), 
     width = $(this).outerWidth(), 
     height = $(this).outerHeight(); 

    if (offset.left < bottomRightX 
      && offset.left + width > topLeftX 
      && offset.top < bottomRightY 
      && offset.top + height > topLeftY) { 
     $(this).addClass('selected'); 
    } 
    else { 
     $(this).removeClass('selected'); 
    } 
}); 

此代碼經過您的文件列表中的所有元素,並運行矩形重疊測試(算法我獲得從this answer)的選擇框和列表元素。使用outerWidth()outerHeight()確保邊框也被考慮在內。

我還注意到,當你鬆開鼠標處理程序,其重置選擇被調用:

$(window).click(function(){ 
    $('.files li').removeClass('selected'); 
}) 

作爲一個可能的解決方案,你可以移動到這一點你mousedown處理。

這裏的jsfiddle這對於我在Chrome 35的工作原理:http://jsfiddle.net/5Hzm4/2/

+0

感謝你的幫助,我真的很感激! – SeinopSys

+0

+1的解釋。這些日子他們正在變成罕見的景象 – Bojangles

相關問題