Disable scrolling when tapping on space button

Disable scrolling with space when not in input fields

目前为 2024-09-10 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Disable scrolling when tapping on space button
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description Disable scrolling with space when not in input fields
  6. // @author MasterMe
  7. // @match *://*/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Check if the target is an input field or a content-editable element
  16. function isInputField(element) {
  17. return element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.isContentEditable;
  18. }
  19.  
  20. // Event listener for keydown
  21. document.addEventListener('keydown', function(e) {
  22. // If the space key is pressed
  23. if (e.code === 'Space') {
  24. const activeElement = document.activeElement;
  25.  
  26. if (isInputField(activeElement)) {
  27. // If in input field, allow the space key to function normally
  28. return;
  29. } else {
  30. // Prevent spacebar from scrolling the page if not in an input field
  31. e.preventDefault();
  32. }
  33. }
  34. }, false);
  35.  
  36. // Additional event listener for keypress to ensure no scrolling
  37. document.addEventListener('keypress', function(e) {
  38. if (e.code === 'Space') {
  39. const activeElement = document.activeElement;
  40.  
  41. if (!isInputField(activeElement)) {
  42. e.preventDefault();
  43. }
  44. }
  45. }, false);
  46. })();