簡體   English   中英

使用jQuery的focus()輸入元素,但光標不會出現

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

我想在單擊div時聚焦輸入元素。

我的HTML看起來像這樣:

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

我的腳本是:

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

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

當我單擊文本框時,占位符文本會正確消失,但閃爍的光標不會顯示在文本框中。 (我無法在文本框中輸入任何文字)

mousedown事件處理程序內部, $(this).children(":first")表達式選擇正確的輸入元素,因此我不知道為什么focus()調用不起作用。

它不適用於mousedown方法; 但它確實可以使用mouseup()click()方法:

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

JS小提琴演示

和:

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

JS小提琴演示

參考文獻:

如果你堅持使用mousedown ,請將焦點延遲到下一個刻度

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

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

mousdown不起作用,使用click

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM