将焦点设置到按键上的下一页元素

时间:2018-08-07 17:36:38

标签: javascript switch-statement keypress

我无法将焦点设置为数据网格中页面的下一个元素。这个想法是,用户将使用箭头键浏览数据网格,但是当按下tab键时,页面上的焦点将从数据网格移动到页面内完全不同的元素上。

我试图让Tab键将焦点设置到下一个页面元素(数据网格之外),但这似乎不适用于我已设置的当前开关情况:

document.querySelector('.ag-body').tabIndex=0;

let lastHeaderCell = false;
document.addEventListener("keydown", function(e) {
  if (e.keyCode == 9 && e.shiftKey == true) {
    let currentFocusedElement = document.activeElement;
    let compId = currentFocusedElement.getAttribute("comp-id");
    currentFocusedElement.classList.add('focus-visible');
    console.log("Shift + Tab currently focused on: ", currentFocusedElement)
    let bodyFocused = document.querySelector('.ag-body').classList.contains('focus-visible');
    if(bodyFocused == true){
      document.querySelector('.ag-cell').classList.add('focus-visible');
    }
  }
  else if(e.key === "ArrowRight"){
    let headerId = document.activeElement.parentElement.parentElement.getAttribute("col-id");
    const headerCell = document.querySelector('.ag-header-cell:last-child').children[1].children[1];
    const hasFocusVisible = document.activeElement.classList.contains('focus-visible');
    if(lastHeaderCell === true) {
      document.querySelector('.ag-cell').focus();
      lastHeaderCell = false;
    }
    else if(headerCell.classList.contains('focus-visible')) {
      lastHeaderCell = true;
    }
  }
  else if(e.key === "ArrowDown"){
    //get column id on arrowdown
    let cellHeaderId = document.activeElement.parentElement.parentElement.getAttribute("col-id");
    document.querySelector('.ag-cell[col-id="' + cellHeaderId + '"]').focus();
  }
  else if(e.key === "ArrowUp") {
    //store value of grid cell column id
    let cellId = document.activeElement.getAttribute("col-id");
    let rowId = document.activeElement.parentElement.getAttribute("row-id");
    //set focus to column header if active cell is in first row and remove body cell focus
    if(rowId === "0"){
      document.querySelector('.ag-cell[col-id="' + cellId + '"]').classList.remove('ag-cell-focus');
      document.querySelector('.ag-header-cell[col-id="' + cellId + '"] .ag-header-cell-label').focus();
    }
  }
  else if(e.key === "Tab"){
    let header = document.querySelector('.ag-header-cell-label').classList.contains('focus-visible');
    console.log("Header has focus visible: ",header)
    //store currently focused cell on tab
    let currentFocusedElement = document.activeElement;
    let compId = currentFocusedElement.getAttribute("comp-id");
    console.log("Currently Focused Element: ",compId);
    //removes focus from current cell
    document.activeElement.blur();
    console.log("Active Element was: ", document.activeElement)
    if(header == true) {
      document.querySelector('.ag-header-cell').tabIndex = -1;
      document.querySelector('.ag-cell[col-id="' + compId + '"]').classList.add('ag-cell-focus');
    }
  }
});

当前网格状态的示例:Link

0 个答案:

没有答案