2016-02-27 215 views
1

我设法让音频在悬停时播放,但当鼠标离开该区域时我无法暂停。暂停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>

+0

小提琴似乎不工作? –

回答

3

您需要使用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/

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

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

+0

您的JavaScript在关闭功能中出现错误。用这个例子,当鼠标悬停时,歌曲播放! – Cuchu

1

stop真的是没有的音频和视频文件处理JavaScript方法。而是使用以下之一:

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

This thread