首页 > 解决方案 > 如何停止甜食中的音频?

问题描述

使用此代码,按钮显示警报并开始播放歌曲,但是单击取消按钮时声音如何停止?

document.querySelector(".first").addEventListener("click", function() {
  swal({
    title: "Show Two Buttons Inside the Alert",
    showCancelButton: true,
    confirmButtonText: "Confirm",
    confirmButtonColor: "#00ff99",
    cancelButtonColor: "#ff0099"
  });
});
    <a id="footer-buttons" class="btn btn-warning btn-sm first" onclick="playAudio()"><span class="fa fa-music"></span> MUSICA</a> 

标签: javascripthtml

解决方案


SweetAlert使用 Promises来检查用户如何与警报交互。如果通过取消单击解除警报,则 Promise 将null作为参数值解决。我下面的示例显示了如何根据用户的选择来控制音频。

let aud = document.getElementById("myAudio");
function swalFnc() {

  aud.play();

  swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    buttons: {
      cancel: {
        visible: true,
        text: 'No, cancel plx!'
      },
      confirm: {
      	visible: true,
        text: 'Yes, delete it!',
        className: 'swal-warning'
      }
    }
  }).then(function(isConfirmed) {
    if (isConfirmed === null) {
      aud.pause();
    }
  });
}
.swal-warning {
  background-color: #DD6B55;
  color: white;
}
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<input type="button" value="Click me" onclick="swalFnc()">
<audio id="myAudio">
  <source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_OOG_5MG.ogg" type="audio/ogg">
  <source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3" type="audio/mp3">
</audio>


推荐阅读