在Div悬停时暂停音频

时间:2016-02-27 22:51:54

标签: javascript jquery html css

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

小提琴: 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>

3 个答案:

答案 0 :(得分:3)

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

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

这会在停止的地方恢复。如果您想从头开始,作为建议的其他答案之一,您需要在audio.currentTime = 0;之前或start调用之后添加pause

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

答案 1 :(得分:1)

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

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

请参阅This thread

答案 2 :(得分:-1)

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

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

相关问题