2016-02-27 214 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