Twitter Bootstrap - 点击时聚焦模态框内的文本区域

70

刚开始尝试使用Bootstrap,感觉非常不错。

我在努力解决一个问题。我有一个反馈的文本框位于模态窗口内,它运作得非常好。但是当你点击按钮激活模态窗口时,我想让焦点放在文本框上,但似乎无法实现。

这里有一个JSFiddle示例: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>

这里是 JS 代码

$('.testBtn').on('click',function(){
    $('#textareaID').focus();
});​

继续 当我单击“启动模态框”时,我希望模态框显示并使焦点在文本区域上。

感谢任何帮助。


可能是推特Bootstrap模态输入框焦点的重复问题。 - Muhammad Rehan Saeed
13个回答

209

因为当您单击按钮时,模态框尚未加载,所以它无法正常工作。 您需要将焦点钩子连接到事件,并访问Bootstrap的模态框页面,我们可以看到事件shown,该事件在模态框已对用户可见时触发(等待CSS转换完成)。 这正是我们想要的。

尝试这个:

$('#myModal').on('shown', function () {
    $('#textareaID').focus();
})
​

这是更新后的示例代码: http://jsfiddle.net/5JN9A/5/


更新:

@MrDBA所指出的,Bootstrap 3中事件名称已更改为shown.bs.modal。因此,在Bootstrap 3中应使用:

$('#myModal').on('shown.bs.modal', function () {
    $('#textareaID').focus();
})

Bootstrap 3的新示例:http://jsfiddle.net/WV5e7/


11
提醒:如果你的模态框具有“淡入淡出”属性,那么根据某些相当晦涩的时间条件(即模态框在完全淡入之前没有足够的存在来接受焦点请求), 这种方法可能无法工作。只有删除淡入淡出属性后,我才能设置模态框项目的焦点,此时我只需要在.show()调用之后立即进行$('#textareaID').focus()调用。可能会因人而异… - Jim Miller
1
谢谢Jim,真的很烦人,为什么焦点没有被设置,但是因为我有一个淡入效果。如果有一个解决方法就太好了。 - chrisb
6
了解,Bootstrap v3已将事件名称更改为shown.bs.modal。 - MrDBA
StackOverflow太棒了,我来到这里,@MrDBA在2小时前评论了Bootstrap v3的更改。谢谢伙计! :) 几乎实时编码胜利! - Leniel Maccaferri
6
请注意事件名称,必须为'shown.bs.modal',而不是'show.bs.modal'。另外,在Chrome的控制台中设置焦点不起作用,因为页面窗口未处于活动状态。为了解决这个问题,您可以使用setTimeout。 - S3RK
显示剩余3条评论

23

我希望有一个声明式的版本,所以我采用了以下方式:

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

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

<input type="text" data-modalfocus />

当模态框弹出时,您的字段将获得焦点。


11

Bootstrap3

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

Bootstrap 2

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

我的模态淡入效果很好,但我不得不将超时时间增加到500毫秒,除此之外,一切都很完美。 - Chris Broski
优秀的通用解决方案,适用于Bootstrap3。高能量! - Aaron Hudon

4
您可以使用 autofocus HTML 元素来设置自动聚焦。
<textarea id="textareaID" autofocus="" ></textarea>

点击这里查看代码演示

(相关内容与IT技术有关)

9
这只在第一次起作用。当对话框关闭(隐藏)并再次显示时,该字段不会获得焦点。 - nevermind

1
正如评论中提到的,您需要从模态框中删除 fade。所以这对我来说有效:
 <div id="myModal" class="modal">
    ...
    <textarea class="form-control" rows="5" id="note"></textarea>
  </div>

  <script>
    $('#myModal').on('shown.bs.modal', function () {
        $('#note').focus();
    })
  </script>

1
我想要更通用一些的东西。
    $(window.document).on('shown.bs.modal', '.modal', function () {
        var timer = window.setTimeout(function () {
            $('.firstInput', this).focus();
            typeof timer !== 'undefined' && window.clearTimeout(timer);
        }.bind(this), 100);
    });

通过这种方式,我可以控制CSS类firstInput的任何控件。设置焦点会有一些轻微的延迟,使其具有某种独特的风格。

1

我在Chrome浏览器上遇到了严重的问题......希望这能帮助到某些人。

//When user clicks link
$('#login-modal-link').on('click',function() {
        setTimeout(function(){
                //If modal has class
            if ($('#login-modal').hasClass('modal')) {
                //Whatever input you want to focus in
                $('#user_login_modal').focus();
            }
        },100);

    });

所有的回复都由于某些原因无法解决问题,所以上面的帖子是我的解决方案,希望能帮到和我有同样问题的人。 - Davis
已在jQuery 1.10.2和Bootstrap v3.0.3中进行测试。 - Davis

1
如果您的模态框具有“fade”属性: 这将起作用,但您可能需要调整超时的持续时间,并显然需要相应的ID:
$("#ID-of-modal").on('show', function(event){
                window.setTimeout(function(){
                  $(event.currentTarget).find('input#ID-of-input').first().focus()
                }, 0175);
              });

0
如果您正在使用Bootstrap v3,并且同时使用模态对话框和wysihtml5文本编辑器,则以下内容适用(假设#basic是您的模态表单的ID):
    $('#basic').on('shown.bs.modal', function () {
    editor.composer.element.focus()
})

0

我不知道为什么,但是选择的解决方案对我不起作用。 我使用以下代码片段代替:

$('#annul-modal').on('show', function() {
    setTimeout(function() {$('textarea:first', '#annul-form').focus();}, 400);
});

我知道它不太好看,但至少它能用... Bootstrap v2.3.0


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接