부트 스트랩 모달 문제-스크롤링이 비활성화 됨


91

모달이 있고 그 모달 내에 큰 숨겨진 콘텐츠를 표시하는 드롭 다운이 있습니다.

이제 첫 번째 모달 위에 쌓인 다음 모달을 열고 닫으면 아래 모달 스크롤이 비활성화됩니다.

내가 직면 한 문제를 복제하는 단계를 포함하여 전체 예제를 만들었습니다. 여기에서 볼 수 있습니다 .

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
    <title></title>
    <style>

    </style>
</head>
<body>


    <input type="button" data-toggle="modal" data-target="#modal_1" class="btn btn-lg btn-primary" value="Open Modal 1" >

    <div class="modal fade" id="modal_1">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">First Modal</h4>
                </div>
                <div class="modal-body">



                    <form class="form">

                        <div class="form-group">
                            <label>1) Open This First: </label>
                            <input type="button" data-toggle="modal" data-target="#modal_2" class="btn btn-primary" value="Open Modal 2" >
                        </div>

                        <div class="form-group">
                            <label>2) Change this once you have opened the modal above.</label>
                            <select id="change" class="form-control">
                                <option value="small">Show Small Content</option>
                                <option value="large">Show Large Content</option>
                            </select>
                        </div> 

                        <div id="large" class='content-div'>
                            <label>Large Textarea Content.. Try and scroll to the bottom..</label>
                            <textarea rows="30" class="form-control"></textarea>

                        </div>

                        <div id="small" class='content-div'>
                            <label> Example Text Box</label> 
                            <input type="text" class="form-control">
                        </div>  


                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="modal_2">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">Second Modal</h4>
                </div>
                <div class="modal-body">

                    <hp>This is the stacked modal.. Close this modal, then chenge the dropdown menu, you cannot scroll... </h5>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>


</body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript"></script>
<script>

    $(document).ready(function() {


        $(".content-div").hide();
        $("#change").change(function() {
            $(".content-div").hide();
            $("#" + $(this).val()).show();
        });


    });

</script>
</html>

동작 동작을 보여주는 Bootply는 다음과 같습니다.

Bootply



스크롤바 문제뿐만 아니라 스타일 문제에 대한 수정 사항 도 포함 된 stackoverflow.com/a/24914782/58241 참조
benrwb

답변:


119

이것은 또한 해결책입니다

.modal {
  overflow-y:auto;
}

http://www.bootply.com/LZBqdq2jl5

자동으로 잘 작동합니다. :) 이것은 실제로 화면 크기보다 높게 실행되는 모달을 수정합니다.


5
이 솔루션은 jQuery에서 모달을 닫고 여는 동안 내 문제를 해결했습니다$('.modal').css('overflow-y', 'auto');
Gla

생명의 구세주) 감사합니다
Victor Gorban

66

모달을 닫으면 태그 modal-open에서를 제거하기 때문 <body>입니다. 부트 스트랩은 같은 페이지에서 여러 모달을 지원하지 않습니다 (적어도 BS3까지).

작동하게하는 한 가지 방법 hidden.bs.modal은 모달을 닫을 때 BS에 의해 트리거 된 이벤트 를 사용한 다음 modal-open, 바디에 클래스 를 강제하기 위해 다른 모달이 열려 있는지 확인하는 것입니다 .

// Hack to enable multiple modals by making sure the .modal-open class
// is set to the <body> when there is at least one modal open left
$('body').on('hidden.bs.modal', function () {
    if($('.modal.in').length > 0)
    {
        $('body').addClass('modal-open');
    }
});

10
(BS4) 작업에 들어갈 수있는 첫 번째 대답은 Bootstrap 4에 ($ ( '. modal.show'). length> 0)을
사용해야했습니다

고마워요-내 문제는 똑같지는 않았지만 귀하의 의견은 페이지 스크롤 작업 손실의 원인 인 body의 modal-open 클래스를 지적했습니다.
Jon

37

나는 당신을위한 해결책을 찾았습니다. 왜 작동하지 않는지 잘 모르겠지만 CSS의 한 줄 코드만으로 문제를 해결할 수 있습니다. 두 번째 모달을 닫은 후 첫 번째 모달이 overflow-y:hidden어떻게 든 얻습니다 . auto실제로 설정하더라도 .

이것을 다시 작성하고 CSS에서 자신의 선언을 설정해야합니다.

#modal_1 {
    overflow-y:scroll;
}

여기에 작동하는 데모가 있습니다.

편집 : 잘못된 링크, 죄송합니다.


작동하지 않는, 그것은 컨테이너 스크롤을하게하지만, 차종 마우스 휠도 stucked
키란 Maniya

19
$(document).ready(function () {

 $('.modal').on("hidden.bs.modal", function (e) { //fire on closing modal box
        if ($('.modal:visible').length) { // check whether parent modal is opend after child modal close
            $('body').addClass('modal-open'); // if open mean length is 1 then add a bootstrap css class to body of the page
        }
    });
});
//this code segment will activate parent modal dialog 
//after child modal box close then scroll problem will automatically fixed

3
IMO 이것은 최선의 답변입니다. overflow-y에 대한 추가 CSS 추가 : auto도 작동하지만 아래에서 언급했듯이 이중 스크롤바가 생성됩니다.
Jacob Rutherford

1
Bootstrap 4.1에서도 작동합니다. 감사
Willi

1
동의합니다. 2-3 답변을 테스트했으며 이것은 Twitter Bootstrap 4.2.1에서 작동합니다.
Tpojka


9

부트 스트랩 4의 경우 추가해야했습니다!

.modal {
    overflow-y: auto !important;
}

그렇지 않으면 작동하지 않고 적용되지 않습니다.

스크린 샷


6

우선, 부트 스트랩은 다중 개방 모달을 지원하지 않습니다. 여기 참조 : Bootstrap Modal 문서

다중 개방 모달은 지원되지 않습니다. 다른 모달이 여전히 보이는 동안에는 모달을 열지 마십시오. 한 번에 둘 이상의 모달을 표시하려면 사용자 정의 코드가 필요합니다.

그러나 필요한 경우 기본 부트 스트랩 스타일 시트 뒤에 포함되는 사용자 정의 스타일 시트에이 CSS를 추가 할 수 있습니다 .

.modal {
    overflow-y:auto;
}

3

제거 data-dismiss="modal" 하고 추가 하여 문제를 해결했습니다.

setTimeout(function(){ $('#myModal2').modal('show') }, 500);
$('#myModal1').modal('hide');

도움이되기를 바랍니다.


덕분에 나는 다른 솔루션이 나를 위해 일하지 않는 이유를 알고하지 않습니다 @Sunny 그러나 이것은 확실히 일한다
DEV-masih

@MasihAkbari 버전 문제 일 수 있습니다. :) 이것도 저를 도와줍니다. BS4를 사용하고 있습니다. 지연으로 인해 약간의 성능 문제가있을 수 있지만 이것은 빠르고 쉬운 수정입니다.
Weijing Jay Lin

3

부트 스트랩은 동시에 여러 모달을 지원하지 않았습니다. 부트 스트랩 버그입니다. BS4에 대한 아래 스크립트를 추가하십시오.

$('body').on('hidden.bs.modal', function () {
if($('.modal.show').length > 0)
{
    $('body').addClass('modal-open');
}
});


2

나는 이것이 트위터 부트 스트랩의 버그 때문이라고 가정합니다. modal-open두 개의 모달이 열려 있어도 몸 에서 클래스 를 제거하는 것 같습니다 . jQuery의 removeClass기능 에 대한 테스트를 수행하고 모달이 아직 열려있는 경우 우회 할 수 있습니다 (기본 기능에 대한 크레딧은이 답변으로 이동 : https://stackoverflow.com/a/1950199/854246 ).

(function(){
    var originalRemoveClassMethod = jQuery.fn.removeClass;

    jQuery.fn.removeClass = function(){
        if (arguments[0] === 'modal-open' && jQuery('.modal.in').length > 1) {
            return this;
        }
        var result = originalRemoveClassMethod.apply( this, arguments );
        return result;
    }
})();


1

이 코드는 두 번째 팝업이 닫히면 첫 번째 팝업이 더 이상 스크롤되지 않습니다.

$('body').on('hidden.bs.modal', '#SecondModal', function (e) {
  if ($('#FirstModal').is(':visible')) { // check if first modal open 
    $('body').addClass('modal-open'); // re-add class 'modal-open' to the body because it was removed when we close the second modal
    $('#FirstModal').focus(); // Focus first modal to activate scrollbar
  }
});

1

일종의 해킹이지만 이상하거나 원하지 않는 동작을 없애기 위해 모달을 닫을 때 닫았다가 다시 여는 것을 좋아합니다. 페이드가 꺼져 있으면 닫히고 다시 열리는 것을 알 수 없습니다.

var $ModalThatWasOnTop= $('#ModalThatWasOnTop')

$ModalThatWasOnTop.on('hidden.bs.modal', function(e) {
     console.log('closing  modal that was on top of the other modal')
     $('#ModalThatWasCovered').modal('hide');
     $('#ModalThatWasCovered').modal('show');

});

0

JQuery를 통해 'modal-open'클래스를 본문에 추가하십시오. 스크롤이 모달을 제외한 모든 작업에서 작동한다고 가정합니다.

이전 응답에 대한 주석으로 : CSS를 통해 모달에 overflow 속성을 추가하면 도움이되지만 페이지에 두 개의 스크롤 막대가 있습니다.



0

나는 실제로 이것에 대한 해결책을 찾았습니다. 을 사용하여 $('#myModal').hide();모델을 숨기려면 실제로 페이지 본문에 대한 스크롤을 활성화해야합니다 . 뒤에 다음 줄을 작성하십시오 $('#myModal').hide();.

$('body').attr("style", "overflow:auto")

그러면 스크롤이 다시 활성화됩니다.


0

bootstrap3 또는 4를 사용하는 경우 html 본문에 modal-open 클래스가 있는지 확인하십시오. 이것이 필수인지 확실하지 않지만 모달 배경의 Z- 색인이 지워 졌는지 확인하십시오.

    $('.your-second-modal').on('hidden.bs.modal', function (e) {
        $('.your-second-modal').css('z-index', "");
        $('.modal-backdrop').css('z-index', 1040);
        $('body').addClass("modal-open");
    });

0

js 코드 아래에 추가하십시오.

    $(document).on("click",".modal",function () {
       if(!$("body").hasClass('modal-open'))
           $("body").addClass('modal-open');
    });
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.