我不明白为什么我的函数无法触发音频。任何建议将不胜感激。
tags$div(
tags$audio(id = 'targetAudio',src = sprintf("audioResources/%s.wav", trialName), type = 'audio/wav'),
tags$button(onclick="document.getElementById('targetAudio').play()",
type = 'button', '',
img(src = paste0(image, 'targetIcon.png'), width = 80, height = 80)),
tags$script("
var target = document.getElementById('targetAudio');
target.onkeydown = function(e) {
if (e.KeyCode === 49) {
target.play();
}
}
")
)
该按钮可正确触发音频,但我还想通过使用键盘上的数字“1”(keycode = 49) 来触发音频。
最佳答案
来自文档:
You must wrap the actual script in HTML to prevent it from being passed as text.
tags$script(HTML("if (window.innerHeight < 400) alert('Screen too small');"))
在你的情况下;
tags$script(HTML("
var target = document.getElementById('targetAudio');
target.onkeydown = function(e) {
if (e.KeyCode === 49) {
target.play();
}
}
")
另请记住,使用 target.onkeydown
您仅在目标元素上监听 keydown 事件。如果你想用全局快捷键播放音频,你可以这样做(当然在 tag$script 里面);
var target = document.getElementById('targetAudio');
document.addEventListener('keydown', listenKey);
function listenKey(e) {
if(e.code === 49){
target.play();
}
}
关于javascript - HTML 使用带有 onkeydown 的键盘快捷键播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64970031/