简体   繁体   English

如何在表中实现箭头导航

[英]how to implement arrow navigation in table with svelte

Given a table with data.selected=[i,j] and with a keydown event listener to change the coordinate based on keyboard arrows, how and where to insert the expression if (i===selected[0] && j = selected[1]) node.focus() ? 鉴于与表data.selected=[i,j]和带keydown事件监听器来改变基于键盘的箭头,在何处以及如何插入表达坐标if (i===selected[0] && j = selected[1]) node.focus()吗?

<table on:keydown='arrow(event.keyCode)'>
  {{#each rows as row, i}}
  <tr>
    {{#each row as val, j}}
    <td tabIndex=1>{{val}}</td>
    {{/each}}
  </tr>
  {{/each}}
</table>

The main handler can change the indices of selected but does not have a reference to the node itself. 主处理程序可以更改selected的索引,但是没有对节点本身的引用。

I've tried inserting the expressions inside the template and in if block but i get errors. 我试过将表达式插入模板以及if block但出现错误。

I would probably do it something like this — put data attributes on the cells themselves, and then use querySelector to find the node to call .focus() on. 我可能会这样做-将数据属性放在单元格本身上,然后使用querySelector查找要调用.focus()的节点。

Here's a demo in the REPL : 这是REPL中的一个演示

<table ref:table>
  {{#each rows as row, i}}
    <tr>
      {{#each row as val, j}}
      <td tabIndex=1>
        <input
          data-row='{{i}}'
          data-col='{{j}}'
          on:keydown='arrow(this, event.keyCode)'
          on:focus='set({selected: [i, j] })'
          bind:value='val'>
      </td>
      {{/each}}
    </tr>
  {{/each}}
</table>

<script>
  export default {
    oncreate () {
      this.observe( 'selected', s => {
        this.refs.table.querySelector( `[data-row="${s[0]}"][data-col="${s[1]}"]` ).focus();
      });
    },
    methods: {
      arrow ( node, code ) {
        if ( code < 37 || code > 40 ) return;

        let i = +node.dataset.row;
        let j = +node.dataset.col;

        const rows = this.get( 'rows' );
        const row = rows[i];

        if ( code === 37 ) j = Math.max( 0, j - 1 );
        if ( code === 39 ) j = Math.min( j + 1, row.length - 1 );
        if ( code === 38 ) i = Math.max( 0, i - 1 );
        if ( code === 40 ) i = Math.min( i + 1, rows.length - 1 );

        this.set({ selected: [ i, j ] });
      }
    }
  };
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM