仅使用脚本将焦点设置为输入

Setting focus on input with script only

我试图将焦点设置在没有显式鼠标事件的文本输入上,只是基于 javascript 的事件。

在 运行 我的脚本之后,我希望输入被突出显示并且光标栏出现。

单击运行相同代码的按钮将产生所需的结果。

问题是我怎样才能用纯事件做到这一点?

更新:我正在重新创建一个我无法控制正在发布的 HTML 的情况。抱歉遗漏了那部分。

var input = document.querySelector("input");
var btn = document.querySelector("#btn");

btn.addEventListener("click", function(event){
  //when triggered by a mouse click on the button, produces desired result
  console.log("click");
  input.focus();
});

setTimeout(function(e){
  var event = new Event("click");
  //does not produce desired result
  btn.dispatchEvent(event);
  //does not produce desired result
  btn.click();
}, 1000);
<input type="text">
<button id="btn">button</button>

as per this fiddle

我不确定您在谈论什么事件,但是您可以在 body onload 属性中的页面加载时调用脚本?这将在您加载页面时突出显示输入,例如:

   <html>
     <body onload='document.querySelector("input").focus()'>
       <input type="text" />
     </body>
   </html>

See this fiddle

您的代码运行良好,只是在 jsFiddle 或 Stack Overflow 代码段 iframe 中运行不佳。

原因是当您单击 "Run" 时,您实际上将焦点转移到另一个页面(另一个 window 元素)。因此,在超时模拟按钮点击后,您的元素聚焦正常,但您的页面没有聚焦,因此您看不到它。

您可以尝试将延迟设置为 5 秒,然后在超时模拟点击之前点击预览中的任意位置 window,您将看到您的输入将获得焦点,就像点击按钮时一样.您还可以使用 document.activeElement

访问当前焦点元素

var input = document.querySelector("input");

var btn = document.querySelector("#btn");

console.log('active element:', document.activeElement);

btn.addEventListener("click", function(event) {
  //when triggered by a mouse click on the button, produces desired result
  console.log("click");
  input.focus();
});

setTimeout(function(e) {
  var event = new Event("click");
  //does not produce desired result
  btn.dispatchEvent(event);
  //does not produce desired result
  btn.click();
  console.log('active element:', document.activeElement);
}, 5000);
<input type="text" />
<button id="btn">
button
</button>

您的代码运行良好。似乎它不仅仅适用于 JS Fiddle。 那么你可以使用 "input type="text" autofocus=true .

如果没有 java 脚本,我们可以使用 css

自动聚焦文本框

https://www.tutorialspoint.com/online_css_editor.php

<head>
    <style>
    input[type=text]:focus{ outline: 3px solid red; }
    </style>
    </head>

   <input type="text" style="height: 28px; width:350px; " autofocus>