Greasy Fork 还支持 简体中文。

Focus input text field on Esc

Focus the first visible input text field when you press Esc key, or restore the previously focused element on second press

目前為 2015-04-27 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Focus input text field on Esc
  3. // @description Focus the first visible input text field when you press Esc key, or restore the previously focused element on second press
  4. // @version 1.0
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. // @run-at document-start
  9. // ==/UserScript==
  10.  
  11. var TEXT_FIELD = ' text number search url ';
  12. var previousElement;
  13. var toFocus;
  14.  
  15. document.addEventListener('keydown', function(e) {
  16. if (e.keyCode != 27 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey)
  17. return;
  18. // find text inputs inside visible DOM containers
  19. var inputs = document.getElementsByTagName('input');
  20. var visible = [];
  21. for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++)
  22. if (TEXT_FIELD.indexOf(' '+input.type+' ') >= 0) {
  23. var n=input, style;
  24. while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
  25. n = n.parentNode;
  26. if (!n || !n.style)
  27. visible.push(input);
  28. }
  29.  
  30. if (visible.length) {
  31. var toFocus = visible[0];
  32. // if empty, try to select an identically named input field with some text (happens on some sites)
  33. if (!toFocus.value)
  34. for (var i in visible)
  35. if (visible[i].value && visible[i].name == toFocus.name &&
  36. (!visible[i].form && !toFocus.form || visible[i].form.action == toFocus.form.action))
  37. toFocus = visible[i];
  38. if (toFocus != document.activeElement) {
  39. // switch to the found input field
  40. previousElement = document.activeElement;
  41. onkeyup(function(){
  42. toFocus.focus();
  43. toFocus.select();
  44. });
  45. } else if (previousElement) {
  46. // restore focus to the element from which we jumped to an input field previously
  47. onkeyup(function(){
  48. document.activeElement.blur(); // in case document.body (page "background") was previously selected
  49. previousElement.focus();
  50. });
  51. }
  52. }
  53.  
  54. // focusing should be done at key-up to prevent the Esc-keydown being also chain-handled by the just focused element
  55. function onkeyup(cb) {
  56. document.addEventListener('keyup', function keyup(e) {
  57. if (e.keyCode == 27) {
  58. document.removeEventListener('keyup', keyup);
  59. cb(e);
  60. }
  61. });
  62. }
  63. });