為所有的影片添加時間
實作
選取所有的影片element,透過dataset取得每部影片的時間,並將回傳的NodeList轉型成Array
const timeNode = Array.from(document.querySelectorAll("[data-time]"));
計算影片的總秒數
const seconds = timeNode .map((node) => node.dataset.time) .map((timeCode) => { const [mins, secs] = timeCode.split(":").map(parseFloat); return mins * 60 + secs; }) .reduce((total, vidSeconds) => total + vidSeconds);
將總秒數轉換成時、分、秒
let secondsLeft = seconds; const hours = Math.floor(secondsLeft / 3600); secondsLeft = secondsLeft % 3600; const minutes = Math.floor(secondsLeft / 60); secondsLeft = secondsLeft % 60; console.log(hours, minutes, secondsLeft);
知識點
querySelectorAll
回傳的是NodeList,裡面並不包含所有Array的API
總結
- 了解如何透過dataset取得element屬性
- Array的map、reduce