单标签音频播放器
以下代码展示单一标签加其伪元素实现音频播放器的基本功能,有进度显示、音频时间信息和动态控制按钮——
<style> /* 播放器id选择器 */ #mplayer { margin: 20px; width: 250px; height: 50px; text-align: justify; text-align-last: justify; font: normal 14px / 40px sans-serif; color: #4d87d0; pointer-events: none; position: relative; --prg: 0%; } /* 伪元素公共属性 */ #mplayer::before, #mplayer::after { position: absolute; content: ''; cursor: pointer; pointer-events: auto; } /* 伪元素 ::before 做进度条 */ #mplayer::before { width: 100%; height: 30%; bottom: 0; background: radial-gradient(circle at calc(var(--prg) + 4px) 50%, #1d5cb6 4px, transparent 5px, transparent), linear-gradient(to right, #4d87d0, #00ff00, #4d87d0 var(--prg), #aed8e6 0) no-repeat 0 50% / 100% 2px; } /* 伪元素 ::after 做按钮 */ #mplayer::after { width: 30px; height: 30px; left: calc(50% - 15px); top: 6px; clip-path: var(--clip); transition: all .35s; background: #1d5cb6; } /* 按钮鼠标滑过 */ #mplayer:hover::after { background: #ff0000; } /* class选择器 :播放按钮 */ .play { --clip: polygon(20% 20%,20% 80%,80% 50%); display: var(--play); } /* class选择器 :暂停按钮 */ .pause { --clip: polygon(20% 20%,20% 80%,40% 80%,40% 20%,80% 20%,80% 80%,60% 80%,60% 20%); } </style> <div id="mplayer" class="play"></div> <audio id="aud" src="https:xg/xg/music.163.com/song/media/outer/url?id=2062919073" autoplay loop></audio> <script> //函数 :秒 → 分:秒 let toMin = (val) => { if (!val) return '00:00'; let min = parseInt(val / 60), sec = parseFloat(Math.floor(val) % 60); if(sec < 10) sec = '0' + sec; return min + ':' + sec; }; // 函数 :根据播放/暂停状态控制按钮样式 let mState = () => mplayer.className = aud.paused ? 'play' : 'pause'; // 鼠标指针移动显示 tiptop 信息 mplayer.onmousemove = (e) => { mplayer.title = e.offsetY < 0.7 * mplayer.offsetHeight ? '播放/暂停' : '调节进度'; } // 单击事件 :播放/暂停或调节进度 mplayer.onclick = (e) => { if(e.offsetY > 0.7 * mplayer.offsetHeight) { aud.currentTime = e.offsetX * aud.duration / (mplayer.offsetWidth - 5); }else{ aud.paused ? aud.play() : aud.pause(); } } // 监听播放进度 :更新进度条 aud.addEventListener('timeupdate', ()=> { mplayer.style.setProperty('--prg', aud.currentTime / (aud.duration + 10) * 100 + '%'); mplayer.innerText = toMin(aud.currentTime) + ' ' + toMin(aud.duration); }); // 监听暂停事件 aud.addEventListener('pause', () => mState()); //监听播放事件 aud.addEventListener('play', () => mState()); </script>
前一篇: 苏小明 - 军港之夜
下一篇: CSS关键帧动画驱动的时钟
发表评论:
评论列表 [0条]