Mousewhell and keyboard control video HTML5

Add mousewhell & keyboard control to html5 video player.

当前为 2024-10-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Mousewhell and keyboard control video HTML5
  3. // @name:en Mousewhell and keyboard control video HTML5
  4. // @namespace http://tampermonkey.net/
  5. // @version 0.1
  6. // @description Add mousewhell & keyboard control to html5 video player.
  7. // @description:en Add mousewhell & keyboard control to html5 video player.
  8. // @author HoangNam
  9. // @match *://*/*
  10. // @grant none
  11. // @license MIT2
  12. // @downloadURL
  13. // @updateURL
  14. // ==/UserScript==
  15.  
  16.  
  17.  
  18. // Thời gian tua tới/lùi (5 giây)
  19. const seekTime = 2;
  20.  
  21. function handleWheel(event, seekTime) {
  22. // Kiểm tra xem sự kiện có phải là sự kiện wheel hay không
  23. if (event.type === 'wheel') {
  24. // Lấy phần tử video hoặc audio đang được trỏ chuột
  25. const isOverMedia = document.querySelector('video, audio');
  26. // Kiểm tra xem con trỏ chuột có trên video hoặc audio hay không
  27. // if (! isOverMedia || ! isOverMedia.contains(event.target))
  28. if (isOverMedia && isOverMedia.contains(event.target)) {
  29. // 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
  30. if (isOverMedia.currentTime !== undefined && isOverMedia.duration !== undefined) {
  31. // Tua tới/lùi 5 giây
  32. if (event.deltaY > 0) {
  33. // Tua tới
  34. isOverMedia.currentTime = Math.max(0, isOverMedia.currentTime - seekTime);
  35. } else {
  36. // Tua lùi
  37. isOverMedia.currentTime = Math.min(isOverMedia.duration, isOverMedia.currentTime + seekTime);
  38. }
  39.  
  40. // Tắt hành động mặc định của chuột
  41. event.preventDefault();
  42. }
  43.  
  44. }
  45. }
  46. }
  47.  
  48. // Thêm event listener cho sự kiện wheel với chế độ passive
  49. document.addEventListener('wheel', (event) => handleWheel(event, seekTime), { passive: false, capture: true });
  50.  
  51. window.addEventListener('load', function() {
  52. document.addEventListener('keydown', function(e) {
  53. console.log(e.keyCode);
  54. var player = document.getElementsByTagName('video')[0];
  55. if (!player) return;
  56.  
  57. switch (e.keyCode) {
  58. case 37:
  59. // Arrow Left lùi 5s
  60. player.currentTime -= e.ctrlKey ? 30 : 5;
  61. break;
  62. case 39:
  63. // Arrow Right tiến 5s
  64. player.currentTime += e.ctrlKey? 30 : 5;
  65. break;
  66. case 32:
  67. // Space tạm dừng
  68. player.paused ? player.play() : player.pause();
  69. break;
  70. }
  71. });
  72. });