为什么这个 textarea 不用 .focus() 聚焦?

新手上路,请多包涵

当用户点击“回复”按钮时,我有这段代码来聚焦文本区域:

     $('#reply_msg').live('mousedown', function() {
        $(this).hide();
        $('#reply_holder').show();
        $('#reply_message').focus();
    });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<div id="reply_msg">
      <div class="replybox">
      <span>Click here to <span class="link">Reply</span></span>
      </div>
      </div>
      <div id="reply_holder" style="display: none;">
      <div id="reply_tab"><img src="images/blank.gif" /> Reply</div>
      <label class="label" for="reply_subject" style="padding-top: 7px; width: 64px; color: #999; font-weight: bold; font-size: 13px;">Subject</label>
      <input type="text" id="reply_subject" class="input" style="width: 799px;" value="Re: <?php echo $info['subject']; ?>" />
      <br /><br />
      <textarea name="reply" id="reply_message" class="input" spellcheck="false"></textarea>
      <br />
      <div id="reply_buttons">
      <button type="button" class="button" id="send_reply">Send</button>
      <button type="button" class="button" id="cancel_reply_msg">Cancel</button>
      <!--<button type="button" class="button" id="save_draft_reply">Save Draft</button>-->
      </div>
    </div>

它显示回复表单,但文本区域不会聚焦。我正在通过 AJAX 添加文本区域,这就是我使用 .live() 的原因。我添加的框显示(我什至通过 AJAX 添加 #reply_msg ,当我将鼠标放在它上面时会发生一些事情)但它不会专注于文本区域。

原文由 Nathan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

在可聚焦元素上单击鼠标会按以下顺序引发事件:

  1. 鼠标按下
  2. 重点
  3. 鼠标弹起
  4. 点击

所以,这是正在发生的事情:

  1. mousedown<a> 提出
  2. 您的事件处理程序试图关注 <textarea>
  3. mousedown 的默认事件行为试图聚焦 <a> (从 <textarea> 焦点)

这是说明此行为的演示:

 $("a,textarea").on("mousedown mouseup click focus blur", function(e) {
  console.log("%s: %s", this.tagName, e.type);
})
$("a").mousedown(function(e) {
  $("textarea").focus();
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)">reply</a>
<textarea></textarea>

那么,我们如何解决这个问题呢?

使用 event.preventDefault() 抑制 mousedown 的默认行为:

 $(document).on("mousedown", "#reply_msg", function(e) {
    e.preventDefault();
    $(this).hide();
    $("#reply_message").show().focus();
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)" id="reply_msg">reply</a>
<textarea id="reply_message"></textarea>

原文由 canon 发布,翻译遵循 CC BY-SA 4.0 许可协议

专注于事件处理程序本身授予焦点的某些内容总是有问题的。一般的解决方案是在超时后设置焦点:

 setTimeout(function() {
  $('#reply_message').focus();
}, 0);

这让浏览器做它的事情,然后你回来把焦点拉到你想要的地方。

原文由 Pointy 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题