programing

Twitter 부트 스트랩 모달 입력 필드 포커스

copysource 2021. 1. 16. 20:40
반응형

Twitter 부트 스트랩 모달 입력 필드 포커스


예제에서 다음과 같은 모달 형식이 있습니다.

<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    Enter something: <input type="text" id="myInput">
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>

모달이 표시된 후 입력 필드에 초점을 맞추고 싶습니다. 이벤트
에 자동 초점과 필드 초점 설정을 모두 시도 $('modal').shown()했습니다. 필드에 초점을 맞추지 만 (필드에 초점을 맞출 때 레이블을 표시하는 또 다른 이벤트가 있습니다) 사실 필드가 초점이 맞지 않아 TAB다시 초점을 맞춰야합니다. 나는 또한 다음과 같은 것을 시도했다.

$(".modal").on('shown', function() {
    $(this).find("[autofocus]:first").focus();
});

autofocus:"autofocus"내 필드에 대한 속성을 설정 합니다. 같은 효과를주었습니다.
내가 시도한 모든 것은 모달이 일반적인 div 일 때 작동하며 페이지로드에 중점을 둡니다. 그러나 모달이 버튼에 의해 트리거되면 아무것도 작동하지 않습니다 (모달이 일반적인 div 일 때에도 로직을 변경하고, 버튼으로 트리거 할 때 그것을 고려하고 그에 따라 해결하려고합니다).

내가 원하는 것은 모달이로드 된 후 필드에 초점이 맞춰져 커서가 깜박이고 사용자가 입력을 시작할 수 있도록하는 것입니다.

작동했던 유일한 것은 bootstrap.js 자체를 변경하는 것입니다. $("#myInput").focus()bootstrap.js 모달 섹션 내부 어딘가에 넣었 지만 그것이 어디에 있는지 잊었습니다. 둘째-bootstrap.js API를 변경하는 것이 좋지 않다고 생각합니다. 더 우아한 솔루션. 제발 조언, xD 감사합니다

업데이트 :
우선, 귀하의 도움에 감사드립니다! 덕분에 내가 가진 문제가 Rails 문제라는 것을 알았습니다.

내가 한 일은 다음과 같습니다.
1). rails generate controller home index
2). 응용 프로그램 / 뷰 / 홈 / index.html을응용 프로그램 / 자산 / 자바 스크립트 / something.js는 이 jsFiddle에 의해 제공에서처럼 robertklep : http://jsfiddle.net/JCaFp/
4). jquery-1.9.1.jsbootstrap.jsapp / assets / javascript /에 있습니다 (둘 다 웹 사이트에서 새로 왔으며 변경된 사항 없음)
5). app / views / layouts / application.html.erb- 이 파일이 우리 솔루션의 핵심이라고 생각합니다.

<!DOCTYPE html>
<html>
<head>
  <title>Udc</title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

여전히 작동하지 않습니다. 모든 js 파일이 포함되지만 브라우저에서 모달을 열면 입력이 잠시 초점을 맞추고 다시 초점이 맞지 않습니다.

나는 또한 이것을 시도했다 :

  <%= javascript_include_tag "jquery" %>
  <%= javascript_include_tag "bootstrap" %>
  <%= javascript_include_tag "somehow" %>

여전히 같은 것.
제안? :)

최신 정보:

해결했습니다!

내 변경 한 후 somehow.js에를

$(document).ready(function() {
    $(".modal").on('shown', function() {
        $(this).find("[autofocus]:first").focus();
    });
});

application.html.erb스타일 시트는 다음 같습니다.

  <%= javascript_include_tag "jquery" %>
  <%= javascript_include_tag "bootstrap" %>
  <%= javascript_include_tag "somehow" %>

예상대로 작동합니다. 다시 한 번 감사드립니다!


게시물 에서 설명한대로 표시된 이벤트 이름이 Bootstrap 3에서 변경 되었다고 생각합니다 .

으로 @MrDBA의 노트, 부트 스트랩 3 이벤트 이름이되어 변경shown.bs.modal.

따라서 Bootstrap 3의 경우 다음을 사용하십시오.

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

각 대화 상자에 대한 특정 코드가 필요하지 않은 일반 솔루션의 경우 다음을 사용할 수 있습니다.

$('.modal').on('shown.bs.modal', function () {
  $(this).find('input:text:visible:first').focus();
})

제거를 시도하면 tabindex="-1"잘 작동합니다.

따라서 이것을 변경하십시오.

<div class="modal fade" id="modalID" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

이에:

<div class="modal fade" id="modalID" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

그냥 변경 $(this).find("[autofocus]:first").focus();하는 $(this).find("#myInput").focus();나를 위해 일했다. Bootstrap API를 변경 한 후 해당 변경 사항을 실행 취소하려면 언제든지 파일을 다시 다운로드하고 교체하면됩니다.


"shown.bs.modal"에 문제가있는 경우 시간 제한을 설정하십시오.

setTimeout(function() {
$('#myInput').focus();
}, 500);

I removed tabindex="-1" and it works so nice.

My HTML code before changes:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

My HTML code after changes:

<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

My Input code:

<input id="tblModalNombreConductor" type="text" maxlength="50" placeholder="Ej: Armando Casas" autofocus/>

And I have no configurations in my Javascript code.


I think the updated answer is pretty clever. Here is another way to solve it.

Bootstrap 3.2's js file includes a script to manage focus during and after the modal's fade transition. This interferes with any jQuery, javascript or rails+HTML5 focusing on a form field in the modal - bootstrap removes your focus after the modal loads.

To remove bootstrap's ability to override your focus, comment out this line in the Modal script area:

transition ?
    that.$element.find('.modal-dialog') // wait for modal to slide in
      .one($.support.transition.end, function () {
        // that.$element.focus().trigger(e)
        // the line above is stealing your focus after modal loads!
      })
      .emulateTransitionEnd(300) :
    that.$element.focus().trigger(e) 

Now your field should be able to have focus in any modal form.


You can do: e.g

<%= f.text_field :first_name, class: "form-control", placeholder: "Enter first name", autofocus: true%>

just add this: autofocus: true


You can also try

$('#the-modal').on('shown.bs.modal', function(e) {
    $('#the-input').focus();
});

ReferenceURL : https://stackoverflow.com/questions/15474862/twitter-bootstrap-modal-input-field-focus

반응형