[英]Click Button on Enter Key
我有一個循環播放聲音列表的腳本,單擊按鈕時一切正常,但是如何讓按鈕在“輸入”時觸發? 我的工作代碼如下:
<div>
<button class="btn-aqua-fxd" id="cycle_button"></button>
</div>
const sounds = ['Power Up', 'Idle', 'Fire!', 'Over Heat!', 'Power Down', 'Party Time!', 'RESET', ];
let sound_index = sounds.length - 1;
const cycle_button = document.getElementById("cycle_button");
//set initial text in button to first sound
cycle_button.innerText = sounds[0];
cycle_button.addEventListener("click", () => {
//get the previous audio and stop it
const last_sound = sounds[sound_index];
const last_audio = document.getElementById(last_sound);
last_audio.pause();
last_audio.currentTime = 0;
//set the sound index to the next one in the sounds list (cycle back if at end)
sound_index = (sound_index + 1) % sounds.length;
const sound = sounds[sound_index];
const audio = document.getElementById(sound);
audio.play();
next_sound = sounds[(sound_index + 1) % sounds.length]
cycle_button.innerText = next_sound;
})
如果沒有jquery,可以在body中添加一個keydown事件監聽器,只有當按下的鍵是回車鍵時才調用cycle_button.click()。
const body = document.querySelector("body")
const cycle_button = document.querySelector("#cycle_button")
body.addEventListener("keydown", (e) => {
if (e.code === "Enter") {
cycle_button.click()
}
})
cycle_button.addEventListener("click", (e) => {
// handle click
})
首先,這不是 java 代碼,而是 javascript。
javascript,這個問題可以用jquery。 例如,您可以嘗試下面的代碼。
const KEY_ENTER = 13;
$("#divId").keyup(function(event) {
if (event.keyCode === KEY_ENTER) {
$("#buttonId").click();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.