首先在网页中嵌入背景音乐,html5代码为:
<script src="http://wuover.qiniudn.com/jquery.js"></script> <a class="mscBtn" id="audioBtn" title=‘最幸福的人‘ style="cursor:pointer;"></a> <audio id="bgMusic" src="http://cctv3.qiniudn.com/zuixingfuderen.mp3" autoplay="autoplay"></audio>
css样式为:
.pause {background-position: 0 bottom;} .mscBtn {height: 50px; background: #fff url(http://cctv2.qiniudn.com/musicbtn.png) no-repeat; display: block;}
通过audio的id即可控制音乐的播放(play())和暂停(pause()),同时通过改变class改变按钮的背景图片,js代码为(切记要引入jq库):
$(function(){ $("#audioBtn").click(function(){ if(music.paused){ music.play(); $("#audioBtn").removeClass("pause").addClass("play"); }else{ music.pause(); $("#audioBtn").removeClass("play").addClass("pause"); } }); });
改进了下,让网页背景音乐支持多首歌曲,播放完在随机播放下一首并且不会和上一首重复
$(function(){ var music = document.getElementById("bgMusic"); var musicArr=[//下面对应歌曲链接和歌名,自行添加用,隔开 {url:‘http://cctv3.qiniudn.com/tbhdqx.mp3‘,title:"唐伯虎点秋香"}, {url:‘http://cctv3.qiniudn.com/abzxh.mp3‘,title:"敖包再相会"}, {url:‘http://cctv3.qiniudn.com/lmzda.mp3‘,title:"辣妹子的爱"}, {url:‘http://cctv3.qiniudn.com/32.mp3‘,title:"32号嫁给你"}, {url:‘http://cctv3.qiniudn.com/tongxinjishou.mp3‘,title:"痛心疾首"}, {url:‘http://cctv3.qiniudn.com/rgangdst.mp3‘,title:"如果爱能感动上天"}, {url:‘http://cctv3.qiniudn.com/cz.mp3‘,title:"车站"}, {url:‘http://cctv3.qiniudn.com/hn.ogg‘,title:"很难"}, {url:‘http://cctv3.qiniudn.com/aqlmysdsc.mp3‘,title:"爱情里没有谁对谁错"}, {url:‘http://cctv3.qiniudn.com/dlaqdln.mp3‘,title:"丢了爱情丢了你"}, {url:‘http://cctv3.qiniudn.com/cty.mp3‘,title:"闯天涯"} ]; $("#audioBtn").click(function(){ if(music.paused){ music.play(); $("#audioBtn").removeClass("pause").addClass("play"); }else{ music.pause(); $("#audioBtn").removeClass("play").addClass("pause"); } }); function randomMusic(){ var isone=$("#bgMusic").attr(‘src‘); var noone=musicArr[parseInt(Math.random()*musicArr.length)]; if (noone.url==isone){ var noone=musicArr[parseInt(Math.random()*musicArr.length)]; } $("#bgMusic").attr(‘src‘,noone.url); $("#audioBtn").attr(‘title‘,noone.title); } randomMusic(); $("#bgMusic").on(‘ended‘,function(){ randomMusic(); }); });