Adding functionality for using the up and down arrow keys to select a table row

后端 未结 4 2207
甜味超标
甜味超标 2021-02-10 15:17

I need the help of an expert on my question below as it exceed and goes well beyond the level of knowledge that I have for programming in JavaScript.

Given the existing

4条回答
  •  执念已碎
    2021-02-10 16:00

    I don't think this actually needs to be that long--you just need to keep the index of the currently highlighted row.

    This has only been tested on Chrome (I don't have IE), but it should work.

    (function() {
    
    
    /**
     * Gets the tr at the specified row or column
     */
    var tbody = document.getElementsByTagName('tbody')[0];
    function getRow(row) {
        return tbody.getElementsByTagName('tr')[row];
    }
    
    // store these so we won't have to keep recalculating
    var numRows = tbody.getElementsByTagName('tr').length;
    
    // index of the currently highlighted row
    var curRow = 0;
    
    // highlight the initially highlighted cell
    getRow(curRow).className = 'highlighted';
    
    
    
    
    // listen for keydown event
    if (addEventListener) {
      window.addEventListener('keydown',keydownHandler, false);
    } else if (window.attachEvent) {
      window.attachEvent('onkeydown', keydownHandler);
    }
    
    
    
    // handle keydown event
    function keydownHandler (evt) {
        // return the old cell to normal
        getRow(curRow).className = 'normal';
    
        // increment/decrement the position of the current cell
        // depending on the key pressed
        if (evt.keyCode == 38 && curRow > 0) // up
            curRow--;
        else if (evt.keyCode == 40 && curRow < numRows-1) // down
            curRow++;
    
        // update the new cell
        getRow(curRow).className = 'highlighted';  
    }
    
    
    })();//end script
    

提交回复
热议问题