【问题标题】:How can I pause music on click?如何在点击时暂停音乐?
【发布时间】:2020-05-17 00:34:35
【问题描述】:

我使用下面的代码(我在网上找到的)在我的网站上单击按钮时播放音频,现在我很好奇如何使音频暂停和/或停止播放什么时候用类似的代码点击同一个按钮?

const rollSound = new Audio("./mp3/SoItGoes.mp3");
$('#Triangle').click(e => rollSound.play());

【问题讨论】:

标签: javascript html jquery css


【解决方案1】:

您可以在按钮上使用一个类来指定播放器的状态(class = "playing" 如果它正在播放,如果它暂停则什么都没有,启动到什么都没有),并在单击按钮时检查它:

HTML:

<button id="Triangle">Play/Pause</button>

JavaScript:

$('#Triangle').click(function(e) {
    if ($(this).hasClass('playing')) {
        rollSound.pause();
        $(this).removeClass('playing');
    } else {
        rollSound.play();
        $(this).addClass('playing');
    }
});

【讨论】:

    【解决方案2】:

    您可以在事件处理程序中使用 if 语句来检查按钮文本值,您可以使用如下内容:

    HTML:

    <button id="Triangle">Play</button>
    

    JS:

    const rollSound = new Audio("./mp3/SoItGoes.mp3");
    $('#Triangle').click((e) => {
      if($('#Triangle').text() === 'Play') {
          rollSound.play();
          $('#Triangle').text('Pause')
      }
      else {
        rollSound.pause();
        $('#Triangle').text('Play')
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多