[英]Dispatch event on an input element while pressing tab key is not working in JavaScript
I am trying to dispatch tab key Press event pro grammatically on a button click.我正在尝试通过单击按钮以编程方式发送 Tab 键 Press 事件。 When the button is clicked, I provided focus for the first input and dispatched key press event with tab key and try to focus the second input.
单击按钮时,我为第一个输入提供了焦点,并使用 Tab 键发送按键事件并尝试聚焦第二个输入。 But unfortunately this is not working.
但不幸的是,这是行不通的。
document.getElementById('btn').addEventListener('click', function() { const input = document.getElementsByTagName('input')[0]; input.focus(); alert('Input 1 focused'); input.dispatchEvent( new KeyboardEvent('keypress', { key: 'tab', code: 'tab', keyCode: 9 }) ); });
<button id="btn">click</button> <input id="default" tabindex="0" /> <br /> <br /> <br /> <input id="default1" tabindex="0" />
I expect upon button click, the second input should be in focus state since I have dispatched tab keypress there.我希望在单击按钮时,第二个输入应该在焦点 state 上,因为我已经在那里发送了 tab 按键。
The reason for this is that your event is not Trusted.原因是您的活动不受信任。
isTrusted
property of the event is false.事件的
isTrusted
属性为 false。 This is a readonly property.这是只读属性。
More details you can find here JavaScript trigger an InputEvent.isTrusted = true您可以在此处找到更多详细信息JavaScript 触发 InputEvent.isTrusted = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.