我读了很多文章,如何在Enter
上从一个输入切换到另一个。许多包含带有自定义指令的解决方案都不好,因为我希望它开箱即用(没有在每个组件上实现指令)。
我只是尝试用键dispatchEvent
呼叫Tab
。但这是行不通的。看起来很简单。我真的希望我不要做一些愚蠢的事情,并且有人可以向我解释为什么 this stackblitz 不起作用。
<input (keyup)="handleChange($event)">
public handleChange(e: KeyboardEvent)
{
if (e && e.keyCode === 13)
{
e.srcElement.dispatchEvent(new KeyboardEvent('keydown', { key: '9' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keypress', { key: '9' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keyup', { key: '9' }));
e.target.dispatchEvent(new KeyboardEvent('keydown', { key: '9' }));
e.target.dispatchEvent(new KeyboardEvent('keypress', { key: '9' }));
e.target.dispatchEvent(new KeyboardEvent('keyup', { key: '9' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keydown', { code: '9' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keypress', { code: '9' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keyup', { code: '9' }));
e.target.dispatchEvent(new KeyboardEvent('keydown', { code: '9' }));
e.target.dispatchEvent(new KeyboardEvent('keypress', { code: '9' }));
e.target.dispatchEvent(new KeyboardEvent('keyup', { code: '9' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keypress', { key: 'Tab' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab' }));
e.target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }));
e.target.dispatchEvent(new KeyboardEvent('keypress', { key: 'Tab' }));
e.target.dispatchEvent(new KeyboardEvent('keyup', { key: 'Tab' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keydown', { code: 'Tab' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keypress', { code: 'Tab' }));
e.srcElement.dispatchEvent(new KeyboardEvent('keyup', { code: 'Tab' }));
e.target.dispatchEvent(new KeyboardEvent('keydown', { code: 'Tab' }));
e.target.dispatchEvent(new KeyboardEvent('keypress', { code: 'Tab' }));
e.target.dispatchEvent(new KeyboardEvent('keyup', { code: 'Tab' }));
console.log("Should move. Event was dispatched on", e.target, e.srcElement);
}
}
答案 0 :(得分:0)
这个答案晚了 3 年,但也许它会帮助某人节省数小时的搜索时间...
看起来dispatchEvent
无法对焦。模拟的 Tab 键的解释与用户按下时不同,因此它不会改变焦点。
您可以编写一个函数来查找下一个(或上一个)可选项卡元素并对其调用 focus()
。请注意,“tabbable”与“focusable”不同——带有 tabindex="-1"
的元素可以通过 focus()
以编程方式聚焦,但用户不能通过选项卡将它们切换到。 Read more about tabbable vs. focusable.
或者,您可以使用现有的解决方案,例如 Joel Purra's EmulateTab。不幸的是它在 jQuery 中,但核心思想是一样的:找到合适的元素并调用 focus()
。