Javascript focus() 输入元素与 jQuery,但光标不出现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12445590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:57:50  来源:igfitidea点击:

focus() input element with jQuery, but the cursor doesn't appear

javascriptjqueryhtmlfocuscursor

提问by Zsolt

I want to focus an input element when a div is clicked.

我想在单击 div 时聚焦输入元素。

My HTML looks like this:

我的 HTML 如下所示:

<div class="placeholder_input">
    <input type="text" id="username" maxlength="100" />
    <div class="placeholder_container">
        <div class="placeholder">username</div>
    </div>
</div>

And my script is:

我的脚本是:

$("#username").focus(function() {
    $(this).next().hide();
});

$(".placeholder_input").mousedown(function() {              
    $(this).children(":first").focus();
});

When I click into the textbox, the placeholder text disappears correctly, but the blinking cursor doesn't show in the textbox. (and I can't type any text into the textbox)

当我单击文本框时,占位符文本正确消失,但闪烁的光标未显示在文本框中。(而且我无法在文本框中输入任何文本)

Inside of the mousedownevent handler, the $(this).children(":first")expression selects the correct input element, so I have no idea why the focus()call doesn't work.

mousedown事件处理程序内部,$(this).children(":first")表达式选择正确的输入元素,所以我不知道为什么focus()调用不起作用。

采纳答案by David says reinstate Monica

It doesn't work with the mousedownmethod; it does, though, work with the mouseup()and click()methods:

它不适用于该mousedown方法;不过,它确实适用于mouseup()click()方法:

$(".placeholder_input").mouseup(function() {              
    $(this).children(":first").focus();
});?

JS Fiddle demo.

JS小提琴演示

And:

和:

$(".placeholder_input").click(function() {              
    $(this).children(":first").focus();
});?

JS Fiddle demo.

JS小提琴演示

References:

参考:

回答by bentael

if you insist on using mousedown, delay the focus till the next tick

如果您坚持使用mousedown,请将焦点延迟到下一个滴答声

$(".placeholder_input").mousedown(function() {              
      var $el =  $(this).children(":first");
      setTimeout(function() {
          $el.focus();
      }, 0);
});

http://jsfiddle.net/wpnNY/46/

http://jsfiddle.net/wpnNY/46/

回答by thecodeparadox

mousdownwill not work, use click.

mousdown不会用,用click

$(".placeholder_input").click(function() {              
    $(this).children(":first").focus();
});?