当你想在javascript中使用它们时,你如何规避重复的按键消息,你按住键,但只希望它播放一次
How do you circumvent repeated keydown messages when you want to use them with javascript where you hold the key down but want it only to play once?
我有一段代码,看起来像下面这样,它工作得很好。它的作用是,当鼠标点击一个名为synth的div时,它会启动一个振荡器声音。然后,当鼠标按钮被释放时,它停止播放振荡器。
synth.onmousedown= function () {
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
};
synth.onmouseup = function () {
oscillator.disconnect();
};
然后我添加了下面的代码,这样当用户按下键盘字符时就会触发振荡器。问题是,当键被按住时,它会反复播放,然后当键盘字符被释放时不会停止。我想知道是否有任何库或代码可以用来规避这一点。我们的目标是让最终的结果像鼠标向下/向上的效果,但键盘运动触发的声音。谢谢你。
$('body').keydown(function() {
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
});
$('body').keyup(function() {
oscillator.disconnect();
});
如果你需要比下面的选项更花哨的东西,你可以使用underscore.js debounce
var keydown = false;
$('body').keydown(function() {
if(!keydown){
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
keydown = true;
}
});
$('body').keyup(function() {
oscillator.disconnect();
keydown = false;
});
这可能是一个变通方法
var keyIsDown = false;
$('body').keydown(function() {
if(keyIsDown) {
// key is already down
return true;
}
keyIsDown = true;
// do your keydown handler
}
$('body').keyup(function() {
keyIsDown = false;
}
相关文章:
- Javascript返回值只在循环中返回一次
- Jquery FadeIn FadeOut 只工作一次
- Javascript html每点击一次就会更改url
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- Rails操作只调用一次,但我在ajax中每秒钟都调用一次
- jQuery滚动功能只工作一次
- 刷新导致我的帖子“;张贴“;再一次
- 引导程序崩溃一次只能看到一个
- 有没有一个抽象层,这样我就可以集成一次,然后使用pusher、pubnub或faye
- 加载器组件仅加载一次
- 根据Angular.JS上一次的内容禁用选择
- 有没有可能的方法可以在一次ASP按钮单击中同时显示JavaScript和服务器端代码中的消息
- 节点.js:一次接收太多UDP消息,丢失它们
- WebShim:一次显示表单验证的所有错误消息
- 在提交时一次内联显示所有验证消息
- jQuery欢迎消息,直到关闭一次(Rails 3)
- 使用 node.js 创建 IRC 机器人.尽管函数只被调用一次,但消息发送两次
- Rails 设置一个 Cookie 以确保只收到一次 Javascript 消息
- Javascript显示弹出消息一次,但它显示每次页面加载
- 当你想在javascript中使用它们时,你如何规避重复的按键消息,你按住键,但只希望它播放一次