開始學習HTML5和css3了,剛學了audio和video標籤就作了一個簡單的同步歌詞的播放器,很簡單,沒什麼技術含量……嘿嘿!css
原理很簡單就是經過給audio添加一個timeupdate事件,每當播放時間改變的時候就獲取當前播放時間來改變歌詞top值,使歌詞上移。
核心JS代碼以下:
- var video = document.querySelector('audio');
- var control = document.querySelector('.scroll p');
- var scroll = document.querySelector('.scroll span');
- var lrc = document.querySelector('.lrc ul')
- var times = document.getElementsByClassName('time');
- var time = [];
- for(var i=0;i<times.length;i++){
- time[i]=times[i].innerText;
- }
- control.onclick = function (){
- if(video.paused){
- video.play();
- control.style.backgroundImage='url(btn1.png)';
- }
- else{
- video.pause();
- control.style.backgroundImage='url(btn2.png)';
- }
- }
- var num=0;
- var top1=30;
- video.addEventListener('timeupdate',function (){
- var t=video.currentTime/video.duration ;
- scroll.style.height=t*300+'px';
- if(t*300>=60){control.style.opacity='0.2';}
- if(t*video.duration>=time[num]&&t*video.duration<=time[num+1]){
- top1-=30;
- num++;
- lrc.style.top=top1+'px';
- }
- else if(t*video.duration>=time[num+1]){top1-=30;num++;console.log(num);}
- else if(t*video.duration<time[num]){top1+=30;num--;}
- },false)