簡體   English   中英

將單元格焦點更改為按鍵

[英]Change cell focus on keypress

我正在努力實現一些我不確定是否會奏效的東西。 我希望做的是在用戶按下任何字母鍵時更改單元格焦點。 我還希望字母出現在源單元格中,而不是出現在目標單元格中​​。 我試圖做的是:

用戶通過單擊來標記單元格

table.onclick = function tableMouseListener(event) {
  markedCell = event.target;
  markedCellRow = markedCell.parentNode.rowIndex;
  markedCellCol = markedCell.cellIndex;
};

用戶在標記的單元格中寫入 A

$(document).keypress(function(e){
  if (e.keyCode == 65) {
    markedCell.appendChild(document.createTextNode(String.fromCharCode(e.keyCode)));
    jumpToNextCell();
  }    
});

輸入 A 后,跳轉到下一個單元格並聚焦它

function jumpToNextCell() {
  table = document.getElementById('myTable');
  markedCellCol++;
  markedCell = table.rows[markedCellRow].cells[markedCellCol];
  markedCell.appendChild(document.createTextNode('\u0020'));
  markedCell.focus();
}

上述邏輯的問題在於,源單元格和目標單元格現在都包含字母 A。

有什么辦法可以防止將字母添加到目標單元格中​​?

編輯

源單元格是我標記的單元格,目標單元格是我要跳轉到的單元格。

按鍵后清除焦點單元格

markedCell.innterText='';

在 JQuery 語法中

$('#markedCellSelector').val('');

我創建了一個實現整個功能的小提琴

這是JS代碼:

var btns = Array.prototype.slice.call(document.querySelectorAll('button')),
    markedBtn;

btns.forEach(function(btn) {
    btn.addEventListener('click', function(){
        btns.forEach(function(btn) {
            btn.classList = Array.prototype.slice.call(btn.classList).filter(function(className) {
                return className !== 'marked';
            });
        });

        btn.className += ' marked';
        markedBtn = this;
    });
});

document.addEventListener('keyup', function(e) {
    var char = String.fromCharCode(e.which);

    if(markedBtn) {
        markedBtn.innerText = char;

        if(markedBtn.nextElementSibling) {
            markedBtn = markedBtn.nextElementSibling;
            markedBtn.click();
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM