gpt4 book ai didi

javascript - 使用 vanilla javascript 单按钮切换音频

转载 作者:行者123 更新时间:2023-11-27 23:19:24 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的按钮来打开和关闭我的音频文件。

一旦我点击播放,我就无法将其关闭。

我使用图像作为按钮,并使用 div.onclick 来触发该函数。

html audio 标签的 ID 为 audioPlay

我使用全局 bool 值playSound,最初设置为false

我的脚本如下所示:

var playSound = false;
if (playSound != true) {
audioButton.src = '../../testStuff/audioPlay.png';
audio.onclick = function () {
document.getElementById('audioPlay').play();
playSound = true;
console.log(playSound);
}
}

if (playSound == true) {
audioButton.src = '../../testStuff/audioStop.png';
audio.onclick = function () {
document.getElementById('audioPlay').pause();
playSound = false;
}
}

当我第一次点击它时,它工作正常。它将 playSound 设置为 true

但是,当我第二次单击它时,什么也没有发生。有些东西正在将 playSound 设置回 false,但我不知道为什么。

我尝试将 ==true if 语句切换到 false 语句之上,并将两个 if 语句滚动到一个语句中onclick 函数,但它仍然以这种方式运行。

有什么想法吗?

最佳答案

我认为问题在于您添加了两个单独的点击处理程序,它们都在每次点击时执行。这会导致 playSound 始终设置为 true,但随后立即设置回 false

相反,编写一个名为 togglePlay 的函数来执行类似以下操作,并将其设置为您的点击处理程序,但仅一次。

    function togglePlay () {      if (playSound) {        audioButton.src = '../../testStuff/audioStop.png';        document.getElementById('audioPlay').pause();        playSound = false;      } else {        audioButton.src = '../../testStuff/audioPlay.png';        document.getElementById('audioPlay').play();        playSound = true;      }    }

关于javascript - 使用 vanilla javascript 单按钮切换音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35513786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com