programing

Twitter 부트스트랩 모달 창 닫기 허용 안 함

batch 2023. 5. 21. 17:41
반응형

Twitter 부트스트랩 모달 창 닫기 허용 안 함

나는 트위터 부트스트랩을 이용하여 모달 창을 만들고 있습니다.기본 동작은 모달 영역 외부를 클릭하면 모달이 자동으로 닫힙니다.이 기능을 사용하지 않도록 설정합니다. 즉, 모달 외부를 클릭할 때 모달 창을 닫지 않습니다.

누군가 이를 위해 jQuery 코드를 공유할 수 있습니까?

배경 값을 정적으로 설정할 것입니다.키를 사용할 때 창이 닫히지 않도록 하려면 다른 값을 설정해야 합니다.

예:

<a data-controls-modal="your_div_id"
   data-backdrop="static"
   data-keyboard="false"
   href="#">

또는 JavaScript를 사용하는 경우:

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});

설정만 하면 됩니다.backdrop'static'.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: true
})

다▁want있▁할 수도 .keyboardfalse키보드의 키를 눌러 모달이 닫히는 것을 방지하기 때문입니다.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
})

myModal모달 내용을 포함하는 디브의 ID입니다.

다음 속성을 모달 정의 자체에 포함할 수도 있습니다.

<div class="modal hide fade" data-keyboard="false" data-backdrop="static">

이미 모달 창을 초기화한 경우 다음을 사용하여 옵션을 재설정할 수 있습니다.$('#myModal').removeData("modal").modal({backdrop: 'static', keyboard: false})새 옵션이 적용되는지 확인합니다.

Dialog의 Bootstrap '숨기기' 이벤트를 재정의하고 기본 동작을 중지합니다(대화 상자를 폐기).

아래 코드 조각을 참조하십시오.

   $('#yourDialogID').on('hide.bs.modal', function(e) {

       e.preventDefault();
   });

우리의 경우에는 잘 작동합니다.

예, 다음과 같이 수행할 수 있습니다.

<div id="myModal"  tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true"
     data-backdrop="static"  data-keyboard="false">

@AymKdn의 답변과 비슷하지만 이것은 모달을 다시 초기화하지 않고 옵션을 변경할 수 있게 해줍니다.

$('#myModal').data('modal').options.keyboard = false;

여러"JavaScript"with여기서 유용합니다!

with ($('#myModal').data("modal").options) {
    backdrop = 'static';
    keyboard = false;
}

모달이 이미 열려 있는 경우 이러한 옵션은 다음 에 모달을 열 때만 적용됩니다.

이 두 가지만 더하면 됩니다.

data-backdrop="static" 
data-keyboard="false"

지금은 이렇게 보일 것입니다.

<div class="modal fade bs-example-modal-sm" id="myModal" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">

그러면 탈출 버튼이 비활성화되고 아무 곳이나 클릭하여 숨깁니다.

페이지에 이 JavaScript를 추가하여 배경의 Click-to-Close 동작을 비활성화하고 모든 Modal에 대해 기본값으로 설정할 수 있습니다(jQuery 및 Bootstrap JS가 로드된 후 실행되는지 확인).

$(function() {
    $.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
});

D3PLOVELER에 따르면 다음 코드가 이 문제를 해결합니다.

$('#modal').removeData('bs.modal').modal({backdrop: 'static', keyboard: false});

& 과 단순히 부트스트랩을 모두 removeData('modal')일을 하지 않습니다.

내가 찾은 최선의 방법은 이 코드를 링크에 추가하는 것입니다.

<!-- Link -->
<a href="#mdl" role="button"  data-backdrop="static" data-keyboard="false" data-toggle="modal" id_team="" ></a>
<-- Div -->
<div id="mdl" class="modal hide fade" tabindex="-1" role="dialog" data-keyboard="false" data-backdrop="static"></div>

bs 5

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
   ...
  </div>
</div>

bs 4.4

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
   ...
  </div>
</div>

그것을 하는 것은 요즘 매우 쉽습니다.추가만 하면 됩니다.

data-backdrop="static" data-keyboard="false" 

당신의 모달 칸막이 안에.

부트스트랩 5에서 특성 이름이 변경되었습니다.다음을 사용할 수 있습니다.

data-bs-backdrop="static" data-bs-keyboard="false"

구글에서 누군가 모달을 닫는 것을 막는 방법을 알아내려고 여기에 오는 사람이 있다면, 모달 오른쪽 상단에 제거해야 하는 닫기 버튼이 있다는 것을 잊지 마세요.

나는 그것을 숨기기 위해 CSS를 사용했습니다.

#Modal .modal-header button.close {
    visibility: hidden;
}

"display: none;"을 사용하면 모달이 작성될 때 덮어쓰므로 사용하지 마십시오.

로 를 backdrop click closing특징.다음 행을 사용하여 다음을 설정할 수 있습니다.backdrop에 대한 선택권.static런타임 중에

부트스트랩 v3.xx

jQuery('#MyModal').data('bs.modal').options.backdrop = 'static';

부트스트랩 v2.xx

jQuery('#MyModal').data('modal').options.backdrop = 'static';

이렇게 이미 이 이게이인모로 표시되는 것을 수.backdrop을 옵설정으로 false(기본 동작), 닫기부터 시작합니다.

아래 코드 줄을 사용하여 모달 팝업의 기본 동작을 설정할 수 있습니다.

 $.fn.modal.prototype.constructor.Constructor.DEFAULTS.backdrop = 'static';

부트스트랩 5에 따라 업데이트된 구문은 다음과 같습니다.
링크

<div class="modal fade" data-bs-backdrop="static" data-bs-keyboard="false" >

자, 이것은 여러분 중 일부가 찾고 있을 수 있는 또 다른 해결책입니다(저도 그랬지만).

제 문제는 비슷했고, 안에 있던 iframe이 로딩되는 동안 모달 상자가 닫혔기 때문에 Iframe이 로딩될 때까지 모달 해제를 비활성화하고 다시 활성화해야 했습니다.

여기에 제시된 솔루션은 100% 작동하지 않았습니다.

제 해결책은 다음과 같습니다.

showLocationModal = function(loc){

    var is_loading = true;

    if(is_loading === true) {

        is_loading  = false;
        var $modal   = $('#locationModal');

        $modal.modal({show:true});

        // prevent Modal to close before the iframe is loaded
        $modal.on("hide", function (e) {
            if(is_loading !== true) {
                e.preventDefault();
                return false
            }
        });

        // populate Modal
        $modal.find('.modal-body iframe').hide().attr('src', location.link).load(function(){

            is_loading = true;
     });
}};

따라서 일시적으로 Modal이 닫히는 것을 방지합니다.

$modal.on("hide", function (e) {
    if(is_loading !== true) {
        e.preventDefault();
        return false
    }
});

그러나 iframe이 로드된 후 닫기를 다시 활성화하는 varis_loading을 사용합니다.

<button type="button" class="btn btn-info btn-md" id="myBtn3">Static 
Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">Static Backdrop</h4>
    </div>
    <div class="modal-body">
      <p>You cannot click outside of this modal to close it.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-
      dismiss="modal">Close</button>
    </div>
   </div>
  </div>
</div>
   <script>
    $("#myBtn3").click(function(){
     $("#myModal3").modal({backdrop: "static"});
    });
   });
  </script>

모드가 표시된 후 부트스트랩 4.1.3의 배경 상태를 업데이트하기 위해 부트스트랩-모달-래퍼 플러그인의 다음 라인을 사용했습니다.플러그인 리포지토리 코드 참조입니다.

$("#yourModalElement").data('bs.modal')._config.backdrop = (true : "static");

다음을 사용하여 줄 바꿈:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="verifyModalLabel" aria-hidden="true">
$(document).ready(function(e){

  $("#modalId").modal({
     backdrop: 'static',
     keyboard: false,
     show: false
  });

});

"backdrop: 'static'"은 외부를 클릭할 때 모달 닫기를 방지합니다. "키보드: false"는 페이지 로드가 완료되면 모달을 이스케이프 키에서 닫을 수 있음을 지정합니다(Esc) "show: false"는 모달을 숨깁니다.

답변으로 제시된 솔루션이 작동하지 않는데, 무슨 문제가 있나요?

$(document).ready(function(){
            $('.modal').modal('show');
            $('.modal').modal({
              backdrop: 'static',
              keyboard: false
            })
        });
<html>
   <head>
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/octicons@8.5.0/index.min.js"></script>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
   </head>
       <body>
       
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <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>
              </div>
              <div class="modal-body">
              </div>
              <div class="modal-footer">
                <div class="text-right"><button type="button" class="btn btn-primary">print</button></div>
            </div>
            </div>
          </div>
        </div>
   </body>
</html>

When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-bs-backdrop="static" data-bs-keyboard="false" for bootstrap 5 and data-backdrop="static" data-keyboard="false" for bootstrap 4

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap 4 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container p-5" >
      <div class="row text-center">
        <div class="col-md-6">
          <!-- Button trigger modal -->
          When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-bs-backdrop="static" data-bs-keyboard="false"
          <button type="button" class="btn btn-primary my-4" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
            Launch static backdrop 5 modal
          </button>

          <!-- Modal -->
          <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  ...
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Understood</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-md-6">
          <!-- Button trigger modal -->
          When backdrop is set to static, the modal will not close when clicking outside it. Click the button below to try it. use data-backdrop="static" data-keyboard="false"
          <button type="button" class="btn btn-primary my-4" data-toggle="modal" data-target="#exampleModal">
            Launch static backdrop 4 modal
          </button>

          <!-- Modal -->
          <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"
          data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                  <button type="button" class="close" data-dismiss="modal" 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" data-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Save changes</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>   
    </div> 
    
    <!-- Bootstrap 5 Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Bootstrap 4 -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"></script>
  </body>
</html>

설하기정으로 설정하세요.static위해서backdrop'정적'입니다.그리고 를 눌러 모달을 닫는 것을 방지합니다.Esckeyboard은 야합해니다설을 설정해야 .false위해서keyboardfalse)을 지정합니다(예: false).

그래서, 코드는 그럴 것입니다.

var jq = jQuery.noConflict();
jq(document).ready(function(){
    jq('#exampleModal').modal({backdrop: 'static', keyboard: false}); 
});

노비타의 답변은 단일 사례에 적용되지만, 이전 사이트에 약 20-30개의 모달이 있으며 부트스트랩으로 여는 모든 모달에 대해 이를 설정하는 답변을 찾고 있었습니다.

모달에 대한 이벤트 네임스페이스를 대상으로 지정하고 모든 부트스트랩 모달에 대한 기본 설정을 추가할 수 있습니다.

모든 모달에 대해 이 작업을 수행하지 않을 수도 있지만, 수행한 경우 각 모달 호출을 정적으로 지정할 필요는 없습니다.

$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this = $(this)
    var href = $this.attr('href')
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
    var option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data(), {backdrop: 'static', keyboard: false})

    e.preventDefault()

    $target
      .modal(option)
      .one('hide', function () {
        $this.focus()
      })
})

제 경우에, 저는 덧붙였습니다.{backdrop: 'static', keyboard: false}선택할 수 있습니다.

언급URL : https://stackoverflow.com/questions/9894339/disallow-twitter-bootstrap-modal-window-from-closing

반응형