如何在Javascript中检测键序列

huangapple go评论66阅读模式
英文:

how to detect a Key Sequence in Javascript

问题

我正在编写一个用户脚本,每次执行快捷键序列 [ctrl + enter] 时在论坛中发布帖子,但我编写的函数将两个按键按独立事件执行,而不是单一序列。

我检查了相关的问题,但没有一个真正解释如何配置函数来处理这个序列。

这是我编写的代码:

let boutton_toast = document.querySelector('.btn-poster-msg');

function toast(e){
    if (e.ctrlKey && e.key == "Enter"){
       boutton_toast.click();
    }
}
document.addEventListener("keydown", toast)

我觉得答案可能非常明显,但我猜不出来。

编辑:

我使用了fordat的方法,它起作用了,这是最终的代码:

let button_toast = document.querySelector('.btn-poster-msg');
let pressedKeys = [];

function bothKeysPressed() {
    if (pressedKeys.includes('Enter') && pressedKeys.includes('Control')) {
        button_toast.click();
    }
}

document.addEventListener('keydown', () => {
    pressedKeys.push(event.key)
    bothKeysPressed();
})

document.addEventListener('keyup', () => {
    pressedKeys = pressedKeys.filter(key => key !== event.key)
})
英文:

i am writing an userscript that post in a forum each time a shortcut sequence is executed [ ctrl + enter ], but the function that i wrote excecutes both keydowns as separate events, and not a single sequence.

i checked the related questions, but none of them really exlained how to configure the function to handle the sequence.

this is the code that i wrote :

let boutton_toast = document.querySelector('.btn-poster-msg');

function toast(e){
    if (e.ctrlKey && e.key=="Enter"){
       boutton_toast.click();
    }
}
document.addEventListener("keydown", toast)

i feel like the answer is really obvious but i can't guess it.

edit :

i used fordat's method and it worked, here's the final code :

let button_toast = document.querySelector('.btn-poster-msg');
        let pressedKeys = [];

        function bothKeysPressed() {
            if (pressedKeys.includes('Enter') && pressedKeys.includes('Control')) {
                button_toast.click();
            }
        }

        document.addEventListener('keydown', () => {
            pressedKeys.push(event.key)
            bothKeysPressed();
        })

        document.addEventListener('keyup', () => {
            pressedKeys = pressedKeys.filter(key => key !== event.key)
        })

答案1

得分: 0

你可以尝试创建一个列表(或任何数据结构),用于存储变量,类似这样:

pressedKeys = [];

function bothKeysPressed() {
    if (pressedKeys.includes('Enter') && pressedKeys.includes('Control')) {
      console.log("Enter and Control are pressed!");
    }
}

document.addEventListener('keydown', () => {
   pressedKeys.push(event.key)
   bothKeysPressed();
})

document.addEventListener('keyup', () => {
   pressedKeys = pressedKeys.filter(key => key !== event.key)
})

然后在你的 "keydown" 监听器中添加一个额外的函数,用于检查你需要的这两个按键。

英文:

You could try creating a list (or any data structure really) that stores the variables, something like this:

pressedKeys = [];

function bothKeysPressed() {
    if (pressedKeys.includes('Enter') && pressedKeys.includes('Control')) {
      console.log("Enter and Control are pressed!");
    }
}

document.addEventListener('keydown', () => {
   pressedKeys.push(event.key)
   bothKeysPressed();
})

document.addEventListener('keyup', () => {
   pressedKeys = pressedKeys.filter(key => key !== event.key)
})

Then just include an additional function in your "keydown" listener that checks for the two keys you need.

答案2

得分: 0

我不确定我明白。

这个肯定有效:

let div = document.querySelector('.test');
let counter = document.querySelector('#counter');
var i=0;
function toast(e){		
    if (!e.repeat && e.ctrlKey && e.key=="Enter"){ // check for e.repeat otherwise if user holds down both keys it calls the function repeatedly 
		//console.log(e)
		let randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);		
        div.style.backgroundColor=randomColor;
		i+=1;
		counter.innerText=i;
	}
}
document.addEventListener("keydown", toast);
<div style="width: 10em; height: 4em; background-color: lightblue" class="test"></div>
<div id="counter">0</div>

你的附加代码缺少一个闭合的 "}"。

请附上一个最小化可重现的示例。

英文:

I'm not sure I follow.

this certainly works:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let div = document.querySelector(&#39;.test&#39;);
let counter = document.querySelector(&#39;#counter&#39;);
var i=0;
function toast(e){		
    if (!e.repeat &amp;&amp; e.ctrlKey &amp;&amp; e.key==&quot;Enter&quot;){ // check for e.repeat otherwise if user holds down both keys it calls the function repeatedly 
		//console.log(e)
		let randomColor = &#39;#&#39; + Math.floor(Math.random()*16777215).toString(16);		
        div.style.backgroundColor=randomColor;
		i+=1;
		counter.innerText=i;
	}
}
document.addEventListener(&quot;keydown&quot;, toast);

<!-- language: lang-html -->

&lt;div style=&quot;width: 10em; height: 4em; background-color: lightblue&quot; class=&quot;test&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;counter&quot;&gt;0&lt;div&gt;

<!-- end snippet -->

You're missing a closing "}" in your attached code.

Please attach a minimal reproducible example.

huangapple
  • 本文由 发表于 2023年7月28日 06:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定