Can Javascript press the Enter key for me?(Javascript 可以为我按 Enter 键吗?)
问题描述
有一个网站,我想在我离开时继续点击进入.有没有可能做类似的事情
There's a site that I want to continue to hit enter on while I'm away. Is it possible to do something like
setInterval(function(){
//have javascript press the button with a certain id
},100);
我想把它放在智能搜索栏中,这样它就可以运行代码了.
I was thinking of just putting that in the smart search bar so it would run the code.
推荐答案
按下回车键会触发一个事件
.您必须弄清楚他们正在听哪个事件侦听器.我将在以下示例中使用 keyup
:
Well pressing enter is triggering an event
. You would have to figure out which event listener they are listening to. I'll use keyup
in the following example:
假设 el
是您想要输入的元素的变量.我不确定你将如何获得该元素,但我相信你知道.
Assume el
is the variable for the element you want enter to be pressed on. I'm not sure how you going to get that element but I'm sure you know.
var evt = new CustomEvent('keyup');
evt.which = 13;
evt.keyCode = 13;
el.dispatchEvent(evt); //This would trigger the event listener.
没有办法真正模拟硬件动作.它只是触发事件监听器.
There's no way to actually simulate a hardware action. It just triggers the event listener.
比如调用el.click()
只是调用事件监听的回调,并不是真正的按键.
For example calling el.click()
is only calling the callback of the event listener, not actually pressing the key.
所以你知道当你给一个元素添加一个事件监听器时,第一个参数是 event
对象.
So you know how when you add an event listener to an element the first argument is the event
object.
el.addEventListener('keyup', function(event) {
//Do Something
});
在 el
如果程序员使用:
el.onkeyup = function(event) {
//do whatever.
}
这非常简单.
只需调用 el.onkeyup(evt);
因为 onkeyup
是一个函数.
为什么我使用 CustomEvent
而不是 KeyboardEvent
因为 new KeyboardEvent('keyup')
返回的是一个具有 属性的对象
和 keyCode
不使用 Object.defineProperty
或 Object.defineProperties
Why did I use CustomEvent
instead of KeyboardEvent
because new KeyboardEvent('keyup')
return's an object with the properties which
and keyCode
that can't be rewritten without the use of Object.defineProperty
or Object.defineProperties
这篇关于Javascript 可以为我按 Enter 键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript 可以为我按 Enter 键吗?
基础教程推荐
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01