問題描述
有一個網站,我想在我離開時繼續點擊進入.有沒有可能做類似的事情
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 鍵嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!