【问题标题】:Twitter bootstrap - Focus on textarea inside a modal on clickTwitter bootstrap - 点击时关注模式内的文本区域
【发布时间】:2012-07-23 00:05:34
【问题描述】:

刚开始玩 bootstrap,真是太棒了。

我正在努力解决这个问题。我在模态窗口中有一个用于反馈的文本区域。它工作得很好。但是当您单击按钮激活模式时,我希望焦点在文本区域上。而且我似乎无法让它工作。

这是一个小提琴: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();
});​

继续 当我单击“启动模式”时,我希望显示模式并将焦点放在 textarea 上。

感谢您的帮助。

【问题讨论】:

标签: javascript jquery twitter-bootstrap focus textarea


【解决方案1】:

它不起作用,因为当您单击按钮时,模式尚未加载。您需要将焦点连接到一个事件,然后转到bootstrap's modals page,我们会看到事件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();
})
​

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


更新:

正如@MrDBA 所说,在 Bootstrap 3 中,事件名称是 changedshown.bs.modal。因此,对于 Bootstrap 3 使用:

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

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

【讨论】:

  • 注意:如果您的模态具有“淡入淡出”属性,则此方法可能不起作用,具体取决于一些看起来非常模糊的时间条件(即,模态不存在的情况)接受焦点请求,直到它完全淡入)。我只能通过删除淡入淡出属性来将焦点设置在模态项上,此时我可以在 .show() 调用之后立即进行 $('#textareaID').focus() 调用。 YMMV,我想...
  • 谢谢吉姆,为什么没有设置焦点真的让我很烦,但那是因为我有淡入。如果有解决方法会很棒。
  • @chrisb 你的意思是在你的模式中添加一个fade 类?它对我有用:jsfiddle.net/5JN9A/16 如果我能看到一个失败的例子,我可以尝试找到一个解决方法:P
  • FYI Bootstrap v3 已将事件名称更改为 shown.bs.modal
  • 注意事件名称。它必须是“shown.bs.modal”,而不是“show.bs.modal”。顺便说一句,在 Chrome 中从控制台设置焦点不起作用,因为页面窗口不活动。要解决它,您可以使用 setTimeout
【解决方案2】:

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

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

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

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

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

【讨论】:

    【解决方案3】:

    Bootstrap3

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

    引导程序 2

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

    【讨论】:

    • 我的模式淡入了,所以我不得不将超时时间增加到 500 毫秒,但除此之外,效果很好。
    • Bootstrap3 的优秀通用修复。高能!
    【解决方案4】:

    您可以使用autofocus html 元素来设置自动对焦。

    <textarea id="textareaID" autofocus="" ></textarea>
    

    Fiddle here (Click)

    【讨论】:

    • 这仅适用于第一次。当对话框关闭(隐藏)并再次显示时,字段不会获得焦点。
    【解决方案5】:

    如果您的 modal 具有 'fade' 属性:

    这可行,但您可能需要调整超时持续时间,显然需要调整 ID:

    $("#ID-of-modal").on('show', function(event){
                    window.setTimeout(function(){
                      $(event.currentTarget).find('input#ID-of-input').first().focus()
                    }, 0175);
                  });
    

    【讨论】:

      【解决方案6】:

      我在 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);
      
          });
      

      【讨论】:

      • 由于某种原因,所有回复都不起作用..所以上面的帖子是我的解决方案,只是有人和我有同样的问题。
      • 在 jQuery 1.10.2 中测试 |引导 v3.0.3
      【解决方案7】:

      正如其中一个 cmets 所述,您需要从模态中删除 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>
      

      【讨论】:

        【解决方案8】:

        我想要一些更通用的东西

            $(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 的任何控制。 设置焦点时会稍有延迟,这赋予了它某种风格。

        【讨论】:

          【解决方案9】:

          我不知道为什么,但选择的解决方案对我不起作用.. 我使用以下代码 sn-p 代替:

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

          我知道它不是很漂亮,但至少它可以工作.. Bootstrap v2.3.0

          【讨论】:

            【解决方案10】:

            如果您使用 bootstrap v3 并且同时使用模态对话框和 wysihtml5 文本编辑器,则以下工作(假设 #basic 是模态表单的 ID):

                $('#basic').on('shown.bs.modal', function () {
                editor.composer.element.focus()
            })
            

            【讨论】:

              【解决方案11】:

              将事件直接附加到模态屏幕对我不起作用。我正在使用此代码:

              $('body').on('shown.bs.modal', '.modal', function () {
                $('[id$=myField]').focus();
              })
              

              使用此代码,我只需将 myField 更改为我想要获得焦点的控件的 id,它还允许我为多个模式屏幕定义焦点,我有类似的东西:

                    $('body').on('shown.bs.modal', '.modal', function () {
                      $('[id$=YesCancel]').focus();
                      $('[id$=YesInverted]').focus();
                      $('[id$=cancelAddCustomer]').focus();
                      $('[id$=closeHistoryModal]').focus();
                    });
              

              来源http://xcellerant.net/2014/08/06/set-focus-on-a-field-when-showing-a-bootstrap-3-modal/

              【讨论】:

              • 为什么不直接使用 $('#myField').focus ?
              • @YvesMartin 你是对的,应该只有一个同名的 id,并且应该按照你指出的那样选择它
              • 是的!这样可行。我直接在模态(即"#modalName")上尝试"shown.bs.modal",但没有触发事件。将它移到身体上是有效的。不幸的是,这意味着如果不进行测试,您实际上并不知道触发了哪个模态......或者像您一样,设置您拥有的任何模态的第一项的焦点。
              【解决方案12】:

              发现在做:

              $(document).on('shown.bs.modal', function () {
                $(this).find('.form-control:visible:first').focus();
              });
              

              工作得很好,因为它只是找到第一个表单控件而不是需要特定的 id 等。这正是大多数时间所需要的。

              【讨论】:

                【解决方案13】:
                <a href="" id="btnmoverCategoriaRaiz">Mover para a raiz...</a> 
                      <script>
                         $(function(){
                            $("#btnmoverCategoriaRaiz").click(function(){
                                $("#novoPlaylist").modal();
                                return false;
                            });
                         });
                
                       </script>    
                 <div id="novoPlaylist" class= "modal  hide">
                          <div class="modal-header">
                            <h3>Novo Playlist</h3>
                          </div>
                          <div class="modal-body">
                            <form class="form-horizontal">
                              <?echo $form->input("Playlist.nome", array("label"=>"Nome:")) ?>
                            </form>
                          </div>
                              <div class="modal-footer">
                                 <a href="javascript:;" class="btn" data-dismiss="modal">Cancelar</a>
                                 <a href="javascript:;" class="btn btn-primary" id="SalvarNomePlaylist" data-loading-text="Aplicando..."> Savar</a>
                              </div>
                      </div>
                

                【讨论】:

                • 你应该包括一些关于你所做的事情的 cmets,而不是强迫人们尝试去寻找变化
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-02-21
                • 2021-06-02
                • 2020-12-20
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多