我想执行 jquery 功能。
在用户的第一次点击时播放一些特定的音频(例如哔声 http://www.soundjay.com/button/beep-07.wav),然后在第二次点击时播放第二个声音(例如猫声 http://static1.grsites.com/archive/sounds/animals/animals021.wav),在第三次点击时播放第三个音频单击等。这是代码。
.contains
有没有办法组合这些功能?
答案 0 :(得分:1)
这是您代码的简单修改版本,它并不完美,但仅供您了解
<body>
<style>
#container{
width:100vw;height:100vh;
background-color:red;
}
</style>
<script>
let clicks = 1;
function play() {
var audio = document.getElementById("audio" + clicks++);
console.log(audio.id)
audio.play();
if (clicks > 3) clicks = 1;
}
</script>
<div id="container" value="PLAY" onclick="play()"> CLICK
<!--SOUND-1-->
<audio id="audio1" src="http://www.soundjay.com/button/beep-07.wav" >
<!--SOUND-2-->
<audio id="audio2" src="http://static1.grsites.com/archive/sounds/animals/animals021.wav" ></audio>
<!--SOUND-3-->
<audio id="audio3" src=" http://static1.grsites.com/archive/sounds/animals/animals011.wav" ></audio>
</body>
答案 1 :(得分:1)
我会做的是这样的:
首先,将此音频标签放入您的正文代码中:<audio id="audio" src="http://www.soundjay.com/button/beep-07.wav" >
然后创建计算按钮点击次数的函数并切换音频元素的 src :
let clickCount = 0;
function play() {
const audio = document.getElementById("audio")
switch(clickCount) {
case 1:
audio.src = "http://static1.grsites.com/archive/sounds/animals/animals021.wav"
break;
case 2:
audio.src = "http://static1.grsites.com/archive/sounds/animals/animals011.wav"
break;
default:
audio.src = "http://www.soundjay.com/button/beep-07.wav";
click = 0;
audio.play();
click += 1;
break;
}
如果我是你的情况,这就是我会做的,但是有很多方法可以做到,请随意使用我的代码:)
答案 2 :(得分:1)
我认为这段代码可以解决您的所有问题,您可以根据需要添加更多 mp3,每当单击播放按钮时,它都会停止现有的 mp3 并连续播放新的 mp3 jsfiddle
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<body>
<style>#container{
width:100vw;height:100vh;
background-color:red;
}</style>
<div id="container">
<button id="play_sound">Click to play</button>
</div>
<script>
const sounds = [
"http://www.soundjay.com/button/beep-07.wav",
"http://static1.grsites.com/archive/sounds/animals/animals021.wav",
"http://static1.grsites.com/archive/sounds/animals/animals011.wav"
];
let soundIndex = 0;
let audio;
$("#play_sound").on("click",()=>{
console.log(sounds[soundIndex])
if(audio){
audio.pause();
audio.currentTime = 0;
}
audio = new Audio(sounds[soundIndex++]);
audio.play();
soundIndex > 2 && (soundIndex = 0);
})
</script>
</body>