2016-04-03 134 views
0

我使用HTML5音頻標籤播放一些背景音樂,並且我希望音樂在用戶滾動某個點時暫停,並在用戶滾動回到頂部時重新開始... 這可能嗎?暫停滾動背景音樂

在此先感謝!

回答

0

如果向下滾動滾動條350px(並在返回頂部時再次播放它),以下示例(普通javascript,無jQuery)會暫停音頻;

window.addEventListener("scroll", myFunction); 
 

 
function myFunction() { 
 
    if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) { 
 
     document.getElementById("player").pause(); 
 
    } else { 
 
     document.getElementById("player").play(); 
 
    } 
 
}
body { 
 
    background: tomato; 
 
}
<audio controls autoplay loop id=player> 
 
    <source src="http://www.youtube.com/audiolibrary_download?vid=7fad087239069cd4" type="audio/mpeg"> 
 
</audio> 
 
<p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p><p>scroll</p>

+1

作品像一個魅力!非常感謝! –

0

可以綁定到scroll事件到窗口並觸發一個foreach爲$('video')並調用pause方法中,當限制和play時偏移爲0

$(window).on('scroll',function(e){ 
    if (document.body.scrollTop === 0) $('video').forEach(function(){this.play()}); 
    if (document.body.scrollTop > 100) $('video').forEach(function(){this.pause()}); 
})