[英]how to implement arrow navigation in table with svelte
鉴于与表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>
主处理程序可以更改selected
的索引,但是没有对节点本身的引用。
我试过将表达式插入模板以及if block
但出现错误。
我可能会这样做-将数据属性放在单元格本身上,然后使用querySelector
查找要调用.focus()
的节点。
<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.