模态弹出式视频,在关闭后继续播放音频



我在网站上制作了一个弹出视频按钮。但是,当我关闭它,或单击模态空间时,音频仍然会继续。

我该如何解决这个问题?我尝试了一些JavaScript功能,但我认为我做错了什么...

谢谢!

// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
      modal.style.display = "none";
  }
}
<button type="button" class="button" id="myBtn">Watch Video</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <span class="close">×</span>
  </div>
  <div class="modal-body">
<iframe width="560" height="315" src="https://www.youtube.com/embed/QH2-TGUlwu4" frameborder="0" allowfullscreen></iframe>
  </div>
  <div class="modal-footer">
  </div>
</div>
</div>

对您来说最简单的方法是重新分配iframe视频src值,以使其自身重置并停止。例如。分配您的iframe示例id="yplayer"的ID,然后使用以下语句要停止并重新加载视频。

document.getElementById('yplayer').src = document.getElementById('yplayer').src;

第二个选项是使用YouTube API函数,该功能将涉及更多代码处理。YouTube API文档

希望这会有所帮助。

您应该在https://www.w3schools.com/tags/av_met_pause.asp

上查看html音频/视频的文档

我建议您更改

span.onclick = function() {
    modal.style.display = "none";
}

使用以下代码

span.onclick = function stopVideo() {
     document.getElementById('video').pause();
}

最新更新