Yang You
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# [Day11] - Custom Video Player(JS30 x 鐵人30 x MDN) ## 來自定義一個影片播放器吧! * 影片嵌入元素:[Video Embed element ](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) * 媒體元素:[HTMLMediaElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) * 影片時間更新事件:[HTMLMediaElement: timeupdate event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event) * 移除事件監聽器:[removeEventListener() method](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) ![](https://cdn.discordapp.com/attachments/1104455124975362148/1145997087213887508/Day11.gif) 今天要來自定義一個影片控制器,因為主要還是學習javascript,樣式的部分就不多加琢磨,直接使用作者給的那些元素進行功能串接吧。 需將這些html元素串接到影片播放器對應的常見功能,如:切換播放暫停、控制聲音、播放速度、播放時間跳轉等,那我們就會用到各式各樣的[HTMLMediaElement媒體元素](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement)的properties及method,推薦大家還是去MDN快速閱覽一次,或用Javascript取得節點用`console.dir()`印出來觀察看看。 **實作開始** 1. **影片播放及暫停**:平常在觀看YouTube時各位應該可以發現除了影片播放鈕,當你點擊影片視窗任何一處時,都會觸發,所以我們要取得兩這個節點,並把他們放在陣列中用`forEach`都加上針對點擊事件的監聽器,觸發時便會執行`togglePlay()`函式。 ```javascript // <video>影片容器本體,我們很多地方都需要改變它的參數 const video = document.querySelector(".player__video.viewer") // 左下方播放鈕 const playButton = document.querySelector(".player__button.toggle"); // 放在陣列中,並依序添加點擊事件監聽器 [video, playButton].forEach((node) => { node.addEventListener("click", togglePlay); }); // 函式切換播放,利用媒體元素的paused暫停與否狀態,去判斷這次點擊要播放還是暫停 // ,並記得對按鈕圖示進行變更,這邊作者使用文字符號代替icon所以使用textContent function togglePlay() { if (video.paused) { video.play(); playButton.textContent = "▍▍"; } else { video.pause(); playButton.textContent = "►"; } } ``` 2. **音量及播放速率控制**:因為這兩個控制閥都是使用`<input type="range">`且`name`即代表媒體元素的該項特性且可供操作,所以我們先用`querySelectorAll`取得`NodeList`後將它們依序添加input值改變值的事件監聽器,觸發時便會執行`handlePlayerSliderInput()`函式。 ```javascript //volume控制滑塊 & playbackRate控制滑塊 const skipButtonList = document.querySelectorAll(".player__button[data-skip]"); // 依序添加點擊事件監聽器 playerSliderList.forEach((input) => { input.addEventListener("input", handlePlayerSliderInput); }); // 將video媒體元素的這個特性 變更為這個滑塊的當前值 function handlePlayerSliderInput() { video[this.name] = this.value; } ``` 3. **播放時間跳轉(快進倒退)**:一樣因為兩個元素都是button也都是控媒體元素的`currentTime`已播放時間,所以我們先用`querySelectorAll`取得`NodeList`後將它們依序添加click的事件監聽器,`handleSkipButtonClick()`函式。 ```javascript // 2個播放時間跳轉按鈕 const playerSliderList = document.querySelectorAll(".player__slider"); // 依序添加點擊事件監聽器 skipButtonList.forEach((button) => { button.addEventListener("click", handleSkipButtonClick); }); //調整影片當前進度,因為data-skip是字串記得轉成數字 function handleSkipButtonClick() { video.currentTime += Number(this.dataset.skip); } ``` 3. **影片進度條控制**:終於進到這題的大魔王(所以擺到最後),有點多再拆細一點講解,我們一樣先取得節點 ```javascript //進度條容器 const progressContainer = document.querySelector(".progress"); //裡面黃色那條實際反應播放進度的 const progressFilled = document.querySelector(".progress__filled"); ``` * **動態進度條**:觀察作者黃色進度條可以發現是使用`.progress__filled`的`flex-basis`CSS屬性實現進度條的,所以我們可以利用變更這個屬性的百分比來反應播放時間,這邊利用到`timeupdate`這個事件,只要`currentTime`變更都會觸發,既然都有`currentTime`播放時間,那當然有另一個屬性代表影片的總長`duration`,動一下腦就可以知道如何計算現在的播放進度囉! ```javascript // 影片播放、快進倒退、還有等下寫的點擊、拖曳進度條都會觸發這個監聽器 video.addEventListener("timeupdate", updateProgress) // 調整進度條的CSS flex-basis %數 = 算出來的播放進度 function updateProgress() { progressFilled.style.flexBasis = `${(video.currentTime / video.duration) * 100}%`; } ``` * **進度條調整播放時間(點擊)**:依據點擊事件觸發的在`progressContainer`X軸位置 **÷** `progressContainer`的容器總寬度 **×** `video.duration`影片總長度,賦值成影片的`currentTIme`,然後因為又觸發了timeupdate事件,所以進度條的flex-basis會跟著變更。 ```javascript progressContainer.addEventListener("click", handleProgressClick); function handleProgressEvents(e) { video.currentTime = (e.offsetX / progressContainer.clientWidth) * video.duration; } ``` * **進度條調整播放時間(拖曳)**:因為是拖曳必須是在滑鼠按下狀態移動滑鼠才會觸發,所以這裡需要用到相當多的事件監聽器。 ```javascript // 滑鼠按下時才新增 滑鼠移動的事件監聽器 progressContainer.addEventListener("mousedown", handleProgressMouseDown); function handleProgressMouseDown() { progressContainer.addEventListener("mousemove", handleProgressEvents); } // 滑鼠彈起 及 滑鼠離開progressContainer容器則會將滑鼠移動的監聽器移除 progressContainer.addEventListener("mouseup", handleProgressMouseUp); function handleProgressMouseUp() { progressContainer.removeEventListener("mousemove", handleProgressEvents); } progressContainer.addEventListener("mouseleave", handleProgressMouseLeave); function handleProgressMouseLeave() { progressContainer.removeEventListener("mousemove", handleProgressEvents); } ``` 這邊我透過觸發`mousedown`時才會新增`mousemove`的事件監聽器,滑鼠彈起或離開容器時則會再將這個`mousemove`的事件監聽器移除,這樣會相對節省一些效能,而不會只要滑鼠在`progressContainer`容器中滑動時都會一直觸發並判斷要不要更改影片時間。 ### [👉Github Demo頁面👈](https://yang840817.github.io/Javascript-30/11%20-%20Custom%20Video%20Player/) ### [👉好想工作室15th鐵人賽看板👈](https://yang840817.github.io/GoodIdeasStudio-2023ironman/) #### 參考資料 1. Javascript 30 官網 https://javascript30.com/ 2. MDN官網 https://developer.mozilla.org/en-US/ ```JSON "tag": ["15th鐵人賽","Javascript 30"] ```

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully