2016-04-03 136 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()}); 
})