html:
<script src="js/jquery-2.1.3.min.js"></script>
<div id="soundIconPlay" onclick="soundIconOff()" class="soundIcon soundIconPlay"></div>
<div id="soundIconOff" onclick="soundIconPlay()" class="soundIcon soundIconOff hide"></div>
<div class="audio" style="width:0; height:0px; overflow:hidden; text-indent:-999px;">
<audio id="bgmusic" loop="loop" autoplay="autoplay" src="data:images/bgmusic.mp3" controls=true></audio>
</div>
//关键: 先写页面再引js,否则会报Cannot read property 'pause/play' of null
<script type="text/javascript">
function init() {
var myAudio = document.getElementById("bgmusic");
myAudio.addEventListener('ended', loopAudio, false);
}
function loopAudio() {
var myAudio = document.getElementById("bgmusic");
myAudio.play();
}
//加载页面播放背景音乐(ios无法实现,只能模拟触屏实现自动播放)
function audioAutoPlay(id){
var audio = document.getElementById('bgmusic'),
play = function(){
audio.play();
document.removeEventListener("touchstart",play, false);
};
audio.play();
document.addEventListener("WeixinJSBridgeReady", function () {
play();
}, false);
document.addEventListener('YixinJSBridgeReady', function() {
play();
}, false);
document.addEventListener("touchstart",play, false);
}
audioAutoPlay('mybgaudio');
</script>
<script type="text/javascript">
var oAudioOFF = "1";
var oAudio = document.getElementById('bgmusic');
function soundIconPlay(){
oAudioOFF = "1";
oAudio.play();
$('#soundIconPlay').show();
$('#soundIconOff').hide();
};
function soundIconOff(){
oAudioOFF = "0";
oAudio.pause();
$('#soundIconPlay').hide();
$('#soundIconOff').show();
};
</script>
css:
.soundIcon{
position:absolute;
top:.1rem;
right:.1rem;
z-index:1;
}
.soundIconPlay{
width:.4rem;
height:.4rem;
background:url('../images/musicOn.png') no-repeat;
background-size:100%;
animation:bgRotate 1.2s infinite linear;
-o-animation:bgRotate 1.2s infinite linear;
-moz-animation:bgRotate 1.2s infinite linear;
-webkit-animation:bgRotate 1.2s infinite linear
}
.soundIconOff{
width:.4rem;
height:.4rem;
background:url('../images/musicOff.png') no-repeat;
background-size:100%;
animation:initial;
-o-animation:initial;
-moz-animation:initial;
-webkit-animation:initial
}
@keyframes bgRotate{
from{transform:rotate(0deg)}
to{transform:rotate(360deg)}
}
@-webkit-keyframes bgRotate{
from{-webkit-transform:rotate(0deg)}
to{-webkit-transform:rotate(360deg)}
}
@-moz-keyframes bgRotate{
from{-moz-transform:rotate(0deg)}
to{-moz-transform:rotate(360deg)}
}
@-o-keyframes bgRotate{
from{-o-transform:rotate(0deg)}
to{-o-transform:rotate(360deg)}
}