如果另一个语句为真,则取消一个if语句 [英] cancel an if statement if another statement comes true
问题描述
我具有此功能,可以对不同的琴键播放不同的声音.但是,如果我按一个键,然后立即按另一个键,则先前的声音仍会播放.
I have this function that plays different sounds to different keys. But if I press a key, then press another key right away, the previous sound will still play.
我的问题是,播放新声音时如何取消上一个声音?
My question is, how do I cancel the previous sound when a new one is played?
代码如下:
window.addEventListener("keydown", checkKeyPressed, false);
function checkKeyPressed(evt) {
if (evt.keyCode == "81") { //q
document.getElementById('enklyd').play();
}
if (evt.keyCode == "87") { //w
document.getElementById('lyd1').play();
}
if (evt.keyCode == "69") { //e
document.getElementById('lyd2').play();
}
if (evt.keyCode == "82") { //r
document.getElementById('lyd3').play();
}
if (evt.keyCode == "84") { //t
document.getElementById('lyd4').play();
}
if (evt.keyCode == "89") { //y
document.getElementById('lyd5').play();
}
}
推荐答案
这实际上不是停止" if语句的问题,因为它们各自正确地完成了工作.您要停止的是正在播放的声音片段.
This isn't really a matter of "stopping" the if statement because they are individually doing their job correctly. What you want to stop is the sound clip being played.
为此,您可以使用 .pause()
方法,将 .currentTime
设置为 0
,或者我相信您也可以设置音量设为0,然后播放即可.
For this you can use the .pause()
method, set the .currentTime
to 0
, or I believe you can also set the volume to 0 and just let it play out.
如评论中所述,有一些SO问题可能已经回答了这一问题.有没有一种独特的情况无法解决?
As mentioned in a comment, there are a few SO questions that may have already answered this. Is there a unique situation that isn't being answered in those?
这篇关于如果另一个语句为真,则取消一个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!