Autofocus input text field

Autofocus the first visible input text field when a page is loaded

目前为 2015-04-28 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Autofocus input text field
  3. // @description Autofocus the first visible input text field when a page is loaded
  4. // @version 1.0.2
  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.  
  13. document.addEventListener('DOMContentLoaded', function() {
  14. if (TEXT_FIELD.indexOf(document.activeElement.type) >= 0)
  15. return;
  16. // find text inputs inside visible DOM containers
  17. var inputs = document.getElementsByTagName('input');
  18. var visible = [];
  19. for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++)
  20. if (TEXT_FIELD.indexOf(' '+input.type+' ') >= 0) {
  21. var n=input, style;
  22. while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
  23. n = n.parentNode;
  24. if (!n || !n.style) {
  25. visible.push(input);
  26. if (input.value)
  27. break;
  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. break;
  39. }
  40. toFocus.focus();
  41. toFocus.select();
  42. }
  43. });

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址