暂停Div悬停音频
问题描述:
我设法让音频在悬停时播放,但当鼠标离开该区域时我无法暂停。暂停Div悬停音频
小提琴: 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/
答
$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {audio.play();});
});
+0
您的JavaScript在关闭功能中出现错误。用这个例子,当鼠标悬停时,歌曲播放! – Cuchu
小提琴似乎不工作? –