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

前端 未结 6 1256
再見小時候
再見小時候 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

    It's probably not all of the functionality you want, since the question is a bit vague, but he's an attempt at adding Ctrl or Shift+ left mouse button to select or deselect multiple table rows - see demo and code below. Disclaimer: Only tested in Chrome and code can almost certainly be optimised.

    JavaScript

    var lastSelectedRow;
    var trs = document.getElementById('tableStudent').tBodies[0].getElementsByTagName('tr');
    
    // disable text selection
    document.onselectstart = function() {
        return false;
    }
    
    function RowClick(currenttr, lock) {
        if (window.event.ctrlKey) {
            toggleRow(currenttr);
        }
    
        if (window.event.button === 0) {
            if (!window.event.ctrlKey && !window.event.shiftKey) {
                clearAll();
                toggleRow(currenttr);
            }
    
            if (window.event.shiftKey) {
                selectRowsBetweenIndexes([lastSelectedRow.rowIndex, currenttr.rowIndex])
            }
        }
    }
    
    function toggleRow(row) {
        row.className = row.className == 'selected' ? '' : 'selected';
        lastSelectedRow = row;
    }
    
    function selectRowsBetweenIndexes(indexes) {
        indexes.sort(function(a, b) {
            return a - b;
        });
    
        for (var i = indexes[0]; i <= indexes[1]; i++) {
            trs[i-1].className = 'selected';
        }
    }
    
    function clearAll() {
        for (var i = 0; i < trs.length; i++) {
            trs[i].className = '';
        }
    }
    

    HTML

    ID Name Class
    1 John 4th
    2 Jack 5th
    3 Michel 6th
    4 Mike 7th
    5 Yke 8th
    6 4ke 9th
    7 7ke 10th

    CSS

    .selected {
        background: lightBlue
    }
    

    I would also look at addEventListener vs onclick and move the event handler binding out of the HTML and into JavaScript. This is known as Unobtrusive Javascript.

    Resources you might want to read:

    • Retrieve Table Row Index of Current Row
    • disable text selection while pressing 'shift'
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

提交回复
热议问题