프로그래밍 방식으로 부트 스트랩 모달을 어떻게 트리거 할 수 있습니까?


204

내가 여기 가면

http://getbootstrap.com/2.3.2/javascript.html#modals

그리고 '데모 모달 시작'을 클릭하면 예상대로 작동합니다. 가입 프로세스의 일부로 모달을 사용하고 있으며 서버 측 유효성 검사가 관련되어 있습니다. 문제가 있으면 확인 메시지가 표시된 상태로 사용자를 동일한 모달로 리디렉션하고 싶습니다. 현재 사용자가 실제로 클릭하지 않고 모달을 표시하는 방법을 알 수 없습니다. 프로그래밍 방식으로 모델을 시작하려면 어떻게해야합니까?

답변:


365

모달 팝업을 수동으로 표시하려면이 작업을 수행해야합니다

$('#myModal').modal('show');

이전에 초기화해야 show: false수동으로 할 때까지 표시되지 않습니다.

$('#myModal').modal({ show: false})

myModal모달 컨테이너의 ID는 어디에 있습니까 ?


감사. 잘됐다. 그러나 한 가지 관찰은 모달 상자가 열릴 때 스크롤을 재설정하고 페이지 하단에서 모달 상자를 트리거하면 페이지가 맨 위로 스크롤된다는 것입니다. 어떻게 막아야합니까?
divinedragon

@ tdubs : 이상합니다. 작동합니다. 최신 모달 코드 github.com/twitter/bootstrap/blob/master/js/bootstrap-modal.js를 참조하십시오 . 지금까지는 여전히 작동합니다.
Claudio Redi

1
@ClaudioRedi, 콘솔에서 두 가지를 모두 시도했지만 크롬을 사용하여 하나만 작동한다는 것을 알았습니다. $ ( '# myModal'). modal ({show : false})는 작동하지 않지만 $ ( '# myModal'). modal ( 'hide')는 작동합니다. 확실하지 않은 이유
Tyrone Wilson

1
$ ( '# myModel'). model ({data : 1, show : false})와 같은 옵션으로 사용자 정의 값 또는 매개 변수를 전달하는 방법이 있습니까?
Anup Sharma

4
@divinedragon은 나중에 나이를 알고 있지만 페이지 상단으로 스크롤하는 문제는 태그와 같은 팝업으로 트리거를 트리거 하거나 핸들러 내부 또는 내부에서 '<a href='#'>실패하기 때문에 발생합니다. 브라우저가 지시대로 작업하고 기본 앵커-페이지 상단으로 스크롤합니다. CSS가 때때로 스타일을 맞추기 위해 세트에 의존하기 때문에 이것을 여러 번 물었 습니다. return falsepreventDefaulthref
brichins

54

버튼과 같이 모달을 트리거 한 요소에 data-toggle = "modal" 을 쓰면 안되며 다음 과 같이 모달을 수동으로 표시 할 수 있습니다.

$('#myModal').modal('show');

다음과 같이 숨 깁니다.

$('#myModal').modal('hide');

데이터 토글로 모달을 여는 URL이 있습니다. 그런 다음 모달 내부에는 마지막으로 제안하는 hide 메소드를 사용하여 모달을 닫는 기능을 호출하는 버튼이 있습니다. 큰!
JayJay

17

프로그래밍 방식의 모달 생성을 찾고 있다면 이것을 좋아할 것입니다.

http://nakupanda.github.io/bootstrap3-dialog/

부트 스트랩의 모달이 모달 생성을위한 자바 스크립트 방법을 제공하더라도 모달의 html 마크 업을 먼저 작성해야합니다.


13

HTML

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

JS

$('button').click(function(){
$('#myModal').modal('show');
});

데모 JS 피들


9

jquery (javascript)를 통해 모델을 보여줄 수 있습니다

$('#yourModalID').modal({
  show: true
})

데모: 여기

또는 "숨기기"클래스를 제거하면됩니다.

<div class="modal" id="yourModalID">
  # modal content
</div>


4

나는 이것을 이렇게하고 싶었고 angular (2/4), 여기 내가 한 일이있다.

<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`

에 대한 중요 사항 참고 :

  • visible 모달의 가시성을 제어하는 ​​컴포넌트의 변수 (부울)입니다.
  • showin부트 스트랩 클래스입니다.

컴포넌트HTML 예제

구성 요소

@ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
@HostListener('document:keydown.escape', ['$event'])
  onEscapeKey(event: KeyboardEvent) {
    this.hideRsvpModal();
  }
..
  hideRsvpModal(event?: Event) {
    if (!event || (event.target as Element).classList.contains('modal')) {
      this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
      this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
      this.renderer.addClass(document.body, 'modal-open');
    }
  }
  showRsvpModal() {
    this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
    this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
    this.renderer.removeClass(document.body, 'modal-open');
  }

HTML

<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="niviteRsvpModalTitle">

                </h5>
                <button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary bg-white text-dark"
                    (click)="hideRsvpModal()">Close</button>
            </div>
        </div>
    </div>
</div>
<!--E:RSVP-->

2

다음 코드는 openModal () 함수에서 모달을 열고 closeModal ()에서 닫는 데 유용합니다.

      function openModal() {
          $(document).ready(function(){
             $("#myModal").modal();
          });
      }

     function closeModal () {
          $(document).ready(function(){
             $("#myModal").modal('hide');
          });  
      }

/ * #myModal은 모달 팝업의 ID입니다 * /


1
답변을 게시 할 때 코드의 기능을 설명하십시오.
Artemis는 여전히
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.