在頁面裏添加音樂文件
<div class="music-icon open">
<audio style="display:none;" id="music" loop="loop" preload="auto" src="image/music.mp3?v=$version$"></audio>
</div>
控制音樂自動播放
// 音樂
backgroundMusic(document.getElementById("music"));
// 音樂播放
function backgroundMusic(audio){
// 自動播放音樂效果,解決瀏覽器或者APP自動播放問題
if(audio.paused){
audio.load();
audio.play();
}
function musicInBrowserHandler() {
if(audio.paused){
audio.load();
audio.play();
}
document.body.removeEventListener('touchstart', musicInBrowserHandler);
}
document.body.addEventListener('touchstart', musicInBrowserHandler);
// 自動播放音樂效果,解決微信自動播放問題
function musicInWeixinHandler() {
if(audio.paused){
audio.load();
audio.play();
}
document.addEventListener("WeixinJSBridgeReady", function () {
if(audio.paused){
audio.load();
audio.play();
}
}, false);
document.removeEventListener('DOMContentLoaded', musicInWeixinHandler);
}
document.addEventListener('DOMContentLoaded', musicInWeixinHandler);
}
css 樣式控制音樂小圖標的樣式
.music-icon {
/* display: none; */
z-index: 999;
width: .82rem;
height: .82rem;
position: absolute;
top: .2rem;
right: .1rem;
background: url('../image/music-open.png') no-repeat;
background-position: 0 0;
background-size: .82rem .82rem;
}
.music-icon.open{
background: url('../image/music-open.png') no-repeat;
background-size: .82rem .82rem;
}
.music-icon.close{
background: url('../image/music-close.png') no-repeat;
background-size: .82rem .82rem;
}
音樂小圖片點擊控制音樂播放和暫停
$('.music-icon').on('touchstart',function(){
if($('#music')[0].paused){
$(this).removeClass('close').addClass('open');
$('#music')[0].play();
}else{
$(this).removeClass('open').addClass('close');
$('#music')[0].pause();
}
});