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
相关文章