Select multiple HTML table rows with Ctrl+click and Shift+click

前端 未结 6 1259
再見小時候
再見小時候 2021-01-31 20:20

Demo

I want to select multiple rows using Windows Shift and Ctrl keys, like multiple folder selection in Windows.

From table of selected ro

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 21:10

    I made it work with all the Windows 7 explorer behaviors and jquery mouse events.

    http://jsfiddle.net/ubershmekel/nUV23/6/

    Note that:

    • When you just click, you set a pivot for the next shift-click
    • Use Ctrl-Shift to expand your current selection and not pivot like Shift-alone does.
    • Use Ctrl-click to add a pivot, you can use Ctrl-Shift to then expand that selection around the new pivot.

    The js:

    var selectionPivot;
    // 1 for left button, 2 for middle, and 3 for right.
    var LEFT_MOUSE_BUTTON = 1;
    var trs = document.getElementById('tableStudent').tBodies[0].getElementsByTagName('tr');
    var idTds = $('td:first-child');
    idTds.each(function(idx, val) {
        // onselectstart because IE doesn't respect the css `user-select: none;`
        val.onselectstart = function() { return false; };
        $(val).mousedown(function(event) {
            if(event.which != LEFT_MOUSE_BUTTON) {
                return;
            }
            var row = trs[idx];
            if (!event.ctrlKey && !event.shiftKey) {
                clearAll();
                toggleRow(row);
                selectionPivot = row;
                return;
            }
            if (event.ctrlKey && event.shiftKey) {
                selectRowsBetweenIndexes(selectionPivot.rowIndex, row.rowIndex);
                return;
            }
            if (event.ctrlKey) {
                toggleRow(row);
                selectionPivot = row;
            }
            if (event.shiftKey) {
                clearAll();
                selectRowsBetweenIndexes(selectionPivot.rowIndex, row.rowIndex);
            }
        });
    });
    
    function toggleRow(row) {
        row.className = row.className == 'selected' ? '' : 'selected';
    }
    
    function selectRowsBetweenIndexes(ia, ib) {
        var bot = Math.min(ia, ib);
        var top = Math.max(ia, ib);
    
        for (var i = bot; i <= top; i++) {
            trs[i-1].className = 'selected';
        }
    }
    
    function clearAll() {
        for (var i = 0; i < trs.length; i++) {
            trs[i].className = '';
        }
    }
    

    And the CSS:

    .selected {
        background: #bdf;
    }
    
    td:first-child {
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -o-user-select: none;
        user-select: none;
    }
    
    td,th {
        padding: 3px;
        border: 2px solid #aaa;
    }
    
    table {
        border-collapse: collapse;
    }
    

提交回复
热议问题