Javascript Twitter 引导程序 - 单击时专注于模态内的 textarea

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11634809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:37:10  来源:igfitidea点击:

Twitter bootstrap - Focus on textarea inside a modal on click

javascriptjquerytwitter-bootstrapfocustextarea

提问by denislexic

Just starting to play around with bootstrap and it's amazing.

刚开始玩引导程序,这太棒了。

I'm trying to figure this out. I have a textarea for feedback inside a modal window. It works great. But I want the focus to go on the textarea when you click on the button to activate the modal. And I can't seem to get it working.

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

Here is a fiddle: http://jsfiddle.net/denislexic/5JN9A/4/

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

Here is the code:

这是代码:

<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>?

Here is the JS

这是JS

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

To resumeWhen I click on "Launch modal" I want the modal to show up and the focus to go on the textarea.

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

Thanks for any help.

谢谢你的帮助。

回答by scumah

It doesn't work because when you click the button the modal is not loaded yet. You need to hook the focus to an event, and going to the bootstrap's modals pagewe see the event shown, that is fired when the modal has been made visible to the user (will wait for css transitions to complete). And that's exactly what we want.

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

Try this:

尝试这个:

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

Here's your fiddle updated: http://jsfiddle.net/5JN9A/5/

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



Update:

更新:

As @MrDBAnotes, in Bootstrap 3 the event name is changedto shown.bs.modal. So, for Bootstrap 3 use:

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

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

New fiddle for Bootstrap 3: http://jsfiddle.net/WV5e7/

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

回答by Alexandre Roger

I wanted to have a declarative version of this, so I went with the following :

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

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

You can then simply add a data-modalfocus property to your field, like so :

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

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

And when the modal pops-up, your field will get focus.

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

回答by Jonas Sciangula Street

Bootstrap3

引导程序3

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

Bootstrap 2

引导程序 2

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

回答by Chancho

You can use the autofocushtml element to set the autofocus.

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

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

Fiddle here (Click)

在这里小提琴(点击)

回答by Davis

I was having major issues in chrome... I hope this helps someone.

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

    });

回答by Semaj Nekeerv

If your modal has the 'fade' property:

如果您的模态具有 'fade' 属性:

This will work but you might have to adjust the duration of the timeout and obviously the IDs where needed:

这将起作用,但您可能需要调整超时的持续时间以及显然需要的 ID:

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

回答by tokhi

As mentioned in one of the comments you need to remove fadefrom your modal. So this works for me:

正如您需要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>

回答by John Grabauskas

I wanted something a bit more generic

我想要更通用的东西

    $(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);
    });

With this, I give whatever control I want the CSS class firstInput. There is a slight delay in setting focus that gives it a certain flair.

有了这个,我给了我想要的 CSS 类 firstInput 任何控制。设置焦点略有延迟,使其具有一定的天赋。

回答by Juan

Attaching the event directly to the modal screen didn't work for me. I'm using this code instead:

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

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

With this code I only need to change myField for the id of the control I want to have the focus, it also allows me to define the focus for multiple modal screens, I have something like:

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

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

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

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

回答by SimonKiteley

Found doing:

发现做:

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

Worked well as it just finds the first form-control rather than needing a specific id etc. Be just what is needed most of the time.

效果很好,因为它只是找到第一个表单控件而不是需要特定的 id 等。大多数时候都是需要的。