Twitter bootstrap - 专注于点击模式内的textarea

den*_*xic 68 javascript jquery textarea focus twitter-bootstrap

刚刚开始玩bootstrap,这太棒了.

我想弄清楚这一点.我有一个textarea在模态窗口内反馈.它很棒.但是当我点击按钮激活模态时,我希望焦点转到textarea.我似乎无法让它发挥作用.

这是一个小提琴:http://jsfiddle.net/denislexic/5JN9A/4/

这是代码:

<a class="btn testBtn" data-toggle="modal" href="#myModal" >Launch Modal</a>

<div class="modal hide" id="myModal">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
  </div>
  <div class="modal-body">
      <textarea id="textareaID"></textarea>
  </div>
  <div class="modal-footer">
    <a href="#" class="btn" data-dismiss="modal">Close</a>
    <a href="#" class="btn btn-primary">Save changes</a>
  </div>
</div>?
Run Code Online (Sandbox Code Playgroud)

这是JS

$('.testBtn').on('click',function(){
    $('#textareaID').focus();
});?
Run Code Online (Sandbox Code Playgroud)

要恢复 当我点击"启动模式"时,我想要显示模态并将焦点放在textarea上.

谢谢你的帮助.

scu*_*mah 202

它不起作用,因为当您单击按钮时尚未加载模态.您需要挂钩的焦点事件,和去引导的模态页面,我们看到的情况shown,即is fired when the modal has been made visible to the user (will wait for css transitions to complete).而这正是我们想要的.

试试这个:

$('#myModal').on('shown', function () {
    $('#textareaID').focus();
})
?
Run Code Online (Sandbox Code Playgroud)

这是你的小提琴更新:http://jsfiddle.net/5JN9A/5/


更新:

正如@MrDBA所指出的,在Bootstrap 3中,事件名称被更改shown.bs.modal.因此,对于Bootstrap 3使用:

$('#myModal').on('shown.bs.modal', function () {
    $('#textareaID').focus();
})
Run Code Online (Sandbox Code Playgroud)

Bootstrap 3的新小提琴:http://jsfiddle.net/WV5e7/

  • 单挑:如果你的模态具有'淡入'属性,这种方法可能不起作用,这取决于似乎是一些相当模糊的时间条件(即模态不足以接受焦点请求,直到它完全褪色).我只能通过删除淡入淡出属性来设置对模态项的关注,此时我可以在.show()调用之后立即执行$('#textareaID').focus()调用.YMMV,我想...... (11认同)
  • FYI Bootstrap v3已将事件名称更改为shown.bs.modal (6认同)
  • 注意事件名称.它必须是'shown.bs.modal',而不是'show.bs.modal'.而btw从Chrome中的控制台设置焦点不起作用,因为页面窗口未激活.要解决它,您可以使用setTimeout (5认同)
  • 太棒了,万分感谢.完美答案. (2认同)

Ale*_*ger 21

我想要一个声明版本,所以我选择了以下内容:

$(document).ready(function() {
    $(".modal").on('shown.bs.modal', function () {
        $("[data-modalfocus]", this).focus();
    });
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地向您的字段添加data-modalfocus属性,如下所示:

<input type="text" data-modalfocus />
Run Code Online (Sandbox Code Playgroud)

当模态弹出时,你的领域将获得焦点.


Jon*_*eet 11

Bootstrap3

$(window.document).on('shown.bs.modal', '.modal', function() {
    window.setTimeout(function() {
        $('[autofocus]', this).focus();
    }.bind(this), 100);
});
Run Code Online (Sandbox Code Playgroud)

Bootstrap 2

$(window.document).on('shown', '.modal', function() {
    window.setTimeout(function() {
        $('[autofocus]', this).focus();
    }.bind(this), 100);
});
Run Code Online (Sandbox Code Playgroud)