JS30 day28 - Video Speed Controller
作業內容
今天的作業是做出一個 bar 在影片旁邊,可以拉動調整影片速度,比較特別的是他是用純 div 做的而不是 input range
說實在這次的還滿簡單的,幾乎可以自己把它做完,自己在做的時候就只有卡在不知道怎麼顯示倍數的文字而已
學到什麼
-
JS
- 要怎麼換算倍率跟百分比?
首先拿到目前 mouse event 的高度,除以整個 bar 的高度得到百分比
1 2 3
| let startY = e.pageY - this.offsetTop const percent = startY / this.offsetHeight const height = Math.round(percent * 100) + '%'
|
再來是自訂最大最小倍率乘以百分比
1 2 3 4
| const min = 0.4 const max = 4 const value = min + (max - min) * percent bar.textContent = `${value.toFixed(2)}x`
|
https://github.com/wesbos/JavaScript30
code 內容:
HTML:
1 2 3 4 5 6
| <div class="wrapper"> <video class="flex" width="765" height="430" src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" loop controls></video> <div class="speed"> <div class="speed-bar">1×</div> </div> </div>
|
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #4C4C4C url('https://unsplash.it/1500/900?image=1021'); background-size: cover; font-family: sans-serif; }
.wrapper { width: 850px; display: flex; }
video { box-shadow: 0 0 1px 3px rgba(0,0,0,0.1); }
.speed { background: #efefef; flex: 1; display: flex; align-items: flex-start; margin: 10px; border-radius: 50px; box-shadow: 0 0 1px 3px rgba(0,0,0,0.1); overflow: hidden; }
.speed-bar { width: 100%; background: linear-gradient(-170deg, #2376ae 0%, #c16ecf 100%); text-shadow: 1px 1px 0 rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center; padding: 2px; color: white; height: 16.3%; }
|
JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const video = document.querySelector('.flex') const bar = document.querySelector('.speed-bar') const speed = document.querySelector('.speed') let isDown = false
speed.addEventListener('mousemove', function(e){ if(!isDown) return; let startY = e.pageY - this.offsetTop const percent = startY / this.offsetHeight const height = Math.round(percent * 100) + '%' bar.style.height = height
const min = 0.4 const max = 4 const value = min + (max - min) * percent bar.textContent = `${value.toFixed(2)}x` video.playbackRate = value }) speed.addEventListener('mousedown', ()=>{ isDown = true }) speed.addEventListener('mouseleave', ()=>{ isDown = false }) speed.addEventListener('mouseup', ()=>{ isDown = false })
|