在 Div 悬停时暂停音频

Pausing audio on Div hover

本文关键字:暂停 音频 悬停 Div      更新时间:2023-09-26

我设法让音频在悬停时播放,但当我的鼠标离开该区域时,我无法让它暂停。

小提琴:https://jsfiddle.net/jzhang172/nLm9bxnw/1/

$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {
    audio.play();
  },
(function(){
 audio.stop();
});
});
.box{
  height:500px;
  width:500px;
  display:flex;
  justify-content:center;
  align-items:center;
  font-size:25px;
  color:white;
  background:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio controls id="audio-1">
  <source src="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<div class="box">
If you Hover me, the song will play!
</div>

您需要

使用audio.pause()而不是.stop()。例如:

$(document).ready(function(){
  var audio = $("#audio-1")[0];
  $('.box').on({
    mouseenter: function() {
      audio.play();
    },
    mouseleave: function() {
      audio.pause();
    }
  });
});

这将从停止的地方恢复。如果要从头开始,正如其他答案之一所建议的那样,您需要在start之前或pause调用之后包含audio.currentTime = 0;

JSFiddle: https://jsfiddle.net/nLm9bxnw/7/

stop实际上不是用于音频和视频文件操作的javascript方法。而是使用以下方法之一:

audio.pause();
audio.currentTime = 0;

查看此线程

$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {audio.play();});
});

https://jsfiddle.net/Cuchu/Ln8q8739/