Day28 Video Speed Bar

Demo

我們在day11有練習過客製化的影音播放器,
上次我們是用內建的<input type=range>控制bar(範例已修改好樣式)
這次則是用自製的range bar來操作

對象和事件

所有事件圍都繞在對象.speedmousemove事件上

1
2
3
4
5
6
7
const speed = document.querySelector('.speed')
const speed_bar = document.querySelector('.speed-bar')
const video = document.querySelector('.flex');
function handler(e){
//..
}
speed.addEventListener('mousemove',handler)

取得百分比

1
2
3
4
5
6
function handler(e){
let mouseY = e.pageY - this.offsetTop // 滑鼠在bar裡面的高度
let speed_height = this.offsetHeight // bar的高
let bar_height = (mouseY/speed_height)*100 +'%'
let textval = ((mouseY/speed_height*4)+min).toFixed(2)
}


我們把值轉換成我們要的範圍後
透過.toFixed(N)可以將小數四捨五入取至第N位

渲染到畫面上

1
2
3
speed_bar.style.height = bar_height
speed_bar.textContent = textval + 'x'
video.playbackRate = textval

依序把值傳給指定元素即可

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const speed = document.querySelector('.speed')
const speed_bar = document.querySelector('.speed-bar')
const video = document.querySelector('.flex');
function handler(e){
let mouseY = e.pageY - this.offsetTop // 滑鼠在bar裡面的高度
let speed_height = this.offsetHeight // bar的高
let min = 0.5;//可加可不加,設定最慢播放速度
let bar_height = (mouseY/speed_height)*100 +'%'
let textval = ((mouseY/speed_height*4)+min).toFixed(2)
speed_bar.style.height = bar_height
speed_bar.textContent = textval + 'x'
video.playbackRate = textval
}

speed.addEventListener('mousemove',handler)
0%