Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - Why isn't this textarea focusing with .focus()?

I have this code to focus a textarea when the user clicks on the "Reply" button:

    $('#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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A mouse-click on a focusable element raises events in the following order:

  1. mousedown
  2. focus
  3. mouseup
  4. click

So, here's what's happening:

  1. mousedown is raised by <a>
  2. your event handler attempts to focus the <textarea>
  3. the default event behavior of mousedown tries to focus <a> (which takes focus from the <textarea>)

Here's a demo illustrating this behavior:

$("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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...