Add mousewhell & keyboard control to html5 video player.
当前为
// ==UserScript==
// @name Mousewhell and keyboard control video HTML5
// @name:en Mousewhell and keyboard control video HTML5
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Add mousewhell & keyboard control to html5 video player.
// @description:en Add mousewhell & keyboard control to html5 video player.
// @author HoangNam
// @match *://*/*
// @grant none
// @license MIT2
// @downloadURL
// @updateURL
// ==/UserScript==
// Thời gian tua tới/lùi (5 giây)
const seekTime = 2;
function handleWheel(event, seekTime) {
// Kiểm tra xem sự kiện có phải là sự kiện wheel hay không
if (event.type === 'wheel') {
// Lấy phần tử video hoặc audio đang được trỏ chuột
const isOverMedia = document.querySelector('video, audio');
// Kiểm tra xem con trỏ chuột có trên video hoặc audio hay không
// if (! isOverMedia || ! isOverMedia.contains(event.target))
if (isOverMedia && isOverMedia.contains(event.target)) {
// Kiểm tra xem phần tử media có thể tua được hay không (có currentTime và duration property) trước khi thực hiện các thao tác tua tới/tua lùi
if (isOverMedia.currentTime !== undefined && isOverMedia.duration !== undefined) {
// Tua tới/lùi 5 giây
if (event.deltaY > 0) {
// Tua tới
isOverMedia.currentTime = Math.max(0, isOverMedia.currentTime - seekTime);
} else {
// Tua lùi
isOverMedia.currentTime = Math.min(isOverMedia.duration, isOverMedia.currentTime + seekTime);
}
// Tắt hành động mặc định của chuột
event.preventDefault();
}
}
}
}
// Thêm event listener cho sự kiện wheel với chế độ passive
document.addEventListener('wheel', (event) => handleWheel(event, seekTime), { passive: false, capture: true });
window.addEventListener('load', function() {
document.addEventListener('keydown', function(e) {
console.log(e.keyCode);
var player = document.getElementsByTagName('video')[0];
if (!player) return;
switch (e.keyCode) {
case 37:
// Arrow Left lùi 5s
player.currentTime -= e.ctrlKey ? 30 : 5;
break;
case 39:
// Arrow Right tiến 5s
player.currentTime += e.ctrlKey? 30 : 5;
break;
case 32:
// Space tạm dừng
player.paused ? player.play() : player.pause();
break;
}
});
});