在页面里添加音乐文件

<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();
    }
});

清儿
72 声望0 粉丝

下一篇 »
vuex