【问题标题】:How can I get my cursor into the input box after I set the focus?设置焦点后如何让光标进入输入框?
【发布时间】:2021-05-19 07:08:30
【问题描述】:

我在网站www.RedBubble.com 上使用javascript 将活动光标放置在顶部的搜索框内。我可以通过代码让它聚焦,出现一个弹出窗口。但是在我获得焦点后,我似乎无法让光标出现在框内。

我运行以下命令:

let searchbar = document.querySelector('input[name="query"]');
const focusEvent = new Event('focus');
const selectEvent = new Event('select');
searchbar.dispatchEvent(focusEvent);
searchbar.dispatchEvent(select);

这会导致搜索输入框获得焦点,但光标不会在输入字段内闪烁。如果我在页面上手动单击选项卡或手动单击框中,我会在框中同时获得焦点和光标。但我似乎无法以编程方式重新创建它。

我也曾尝试在开发者控制台之外执行此操作,以防万一这会引起关注,但无论是否激活开发者控制台,我都会得到相同的结果。

【问题讨论】:

    标签: javascript dom-events focus dispatchevent


    【解决方案1】:

    对于光标焦点,试试下面的代码,它可能会有所帮助:

    let searchbar = document.querySelector('input[name="query"]');
    searchbar.focus();
    

    【讨论】:

      【解决方案2】:

      接受的答案here 解释说,分派事件不会生成与分派事件关联的默认操作。

      您需要明确地调用焦点。

      let searchbar = document.querySelector('input[name="query"]');
      searchbar.focus();
      <input name="query"/>

      【讨论】:

        猜你喜欢
        • 2018-12-30
        • 2011-09-27
        • 1970-01-01
        • 2014-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多