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-28 提交的版本。查看 最新版本

  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.3
  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 first;
  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. for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++)
  21. if (TEXT_FIELD.indexOf(' '+input.type+' ') >= 0) {
  22. var n=input, style;
  23. while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
  24. n = n.parentNode;
  25. if (!n || !n.style) {
  26. if (!first // set the first OR if it's empty, try to select an identically named input field with some text (happens on some sites)
  27. || (input.value && input.name == first.name && (!input.form && !first.form || input.form.action == first.form.action))) {
  28. first = input;
  29. if (first.value)
  30. break;
  31. }
  32. }
  33. }
  34.  
  35. if (first) {
  36. if (first != document.activeElement) {
  37. // switch to the found input field
  38. previousElement = document.activeElement;
  39. onkeyup(function(){
  40. first.focus();
  41. first.select();
  42. });
  43. } else if (previousElement) {
  44. // restore focus to the element from which we jumped to an input field previously
  45. onkeyup(function(){
  46. document.activeElement.blur(); // in case document.body (page "background") was previously selected
  47. previousElement.focus();
  48. });
  49. }
  50. }
  51.  
  52. // focusing should be done at key-up to prevent the Esc-keydown being also chain-handled by the just focused element
  53. function onkeyup(cb) {
  54. document.addEventListener('keyup', function keyup(e) {
  55. if (e.keyCode == 27) {
  56. document.removeEventListener('keyup', keyup);
  57. cb(e);
  58. }
  59. });
  60. }
  61. });