JS30 Day 28 筆記


Posted by GL on 2023-05-23

目標

製作一個可以控制影片速率的控制器

Demo

step 1 : 取得 HTML 頁面元素

const video = document.querySelector('.flex')
const speed  = document.querySelector('.speed')
const bar = document.querySelector('.speed-bar')

step 2 : 監聽 mousemove 的事件

function handleMove(e){

}

speed.addEventListener('mousemove',handleMove)

step 3 : mousemove 事件被觸發時,執行 handleMove()

number.toFix(n) : 數字四捨五入到小數點第 n 位

function handleMove(e){
  // 當事件綁在父元素上,觸發到子元素時
  // this => 回傳父元素 ; e.target => 回傳子元素
  // e.pageY:目前滑鼠在 Y 的位置 (隨著滑鼠移動,滑鼠在 bar 元素裡的位置)
  // this.offsetTop: speed 元素距離上方的位置
  // this.offsetHeight:speed 元素本身高度

  const y = e.pageY - this.offsetTop
  const percent = y / this.offsetHeight
  const height = Math.round(percent * 100) + '%'
  // 依照計算出來的位置百分比,設定 speed-bar 樣式的高度
  bar.style.height = height

  const min = 0.4
  const max = 4
  // 設定播放速率的範圍(0.4 倍 ~ 4 倍)
  const playbackRate = percent * (max - min) + min
  // 將速率顯示在 speed-bar 上
  bar.textContent = playbackRate.toFixed(2) + 'x'
  // 用 video.playbackRate 設定影片撥放速度
  video.playbackRate = playbackRate
}

參考資料:


#JS 30







Related Posts

DAY43:Adding Big Numbers

DAY43:Adding Big Numbers

[ Nuxt.js 2.x 系列文章 ] Nuxt.js 套件應用-Swiper

[ Nuxt.js 2.x 系列文章 ] Nuxt.js 套件應用-Swiper

The Zen Programmer 程式設計之禪書摘

The Zen Programmer 程式設計之禪書摘


Comments