I have some HTML / JS application I like to test by injecting dummy user input.
我有一些想要通过注入虚拟用户输入进行测试的HTML/JS应用程序。
I tried to use document.activeElement
to find the INPUT / TEXTAREA I push the simulated input to, but quite often activeElement
just points to document.body
. Entering real keystrokes will let some browser magic happen, that snaps focus to some (the first?) visible INPUT element on the page and put the character just entered there.
我尝试使用Docent.activeElement来查找我将模拟输入推送到的INPUT/TEXTAREA,但非常常见的情况是,activeElement只指向Docent.Body。输入真正的按键将会让一些浏览器变得神奇,这会将焦点集中到一些(第一个?)页面上的可视输入元素,并将刚输入的字符放在那里。
Is this magic always the case, and does this happen in a reliable manner? What JS code will resemble this "magic" ?
这种魔力一直都是这样吗?这种情况是否以一种可靠的方式发生?什么样的JS代码会像这个“魔术”一样?
更多回答
Just typing does not automatically focus an element. You'll need to show your HTML for concrete help.
只需输入并不会自动聚焦元素。您需要显示您的HTML才能获得具体的帮助。
优秀答案推荐
Just use :focus
selector:
只需使用:焦点选择器:
document.addEventListener('keydown', (e, input) => {
console.log(document.querySelector(':focus'));
});
<input>
更多回答
The question was about how to find the element that input would go to in an existing application. So the code should answer the question where the typing would go, not change it!
问题是如何在现有应用程序中找到输入将转到的元素。因此,代码应该回答输入将去哪里的问题,而不是更改它!
@dronus fixed....
@Dronus修复...
我是一名优秀的程序员,十分优秀!