스크롤로 인해 반응 형 테이블 내부의 부트 스트랩 버튼 드롭 다운이 보이지 않음


88

overflow: auto;속성 때문에 드롭 다운이 표시되지 않기 때문에 응답하고 스크롤 할 때 테이블 내부의 드롭 다운 버튼에 문제가 있습니다 . 버튼이 축소되었을 때 드롭 다운 옵션을 표시하려면 어떻게해야합니까? 일부 jQuery를 사용할 수 있지만 왼쪽에서 오른쪽으로 스크롤하는 데 문제가 있으므로 다른 솔루션을 찾기로 결정했습니다. 더 잘 이해하기 위해 사진을 첨부했습니다.여기에 이미지 설명 입력

다음은 작은 js 바이올린입니다.

답변:


60

나는 이것을 스스로 해결했고 동일한 문제를 가진 다른 사용자를 돕기 위해 답변을 범위에 넣었습니다. 부트 스트랩에 이벤트가 있으며 해당 이벤트를 사용하여 설정할 수 overflow: inherit있지만 부모에 CSS 속성이 없으면 작동합니다. 컨테이너.

$('.table-responsive').on('show.bs.dropdown', function () {
     $('.table-responsive').css( "overflow", "inherit" );
});

$('.table-responsive').on('hide.bs.dropdown', function () {
     $('.table-responsive').css( "overflow", "auto" );
})

그리고 이것은 바이올린입니다

info: 이 바이올린 예제에서 이상하게 작동하고 왜 그런지 모르겠지만 내 프로젝트에서는 잘 작동합니다.


3
이것은 줄의 첫 번째 셀에 드롭 다운이있는 테이블에서만 작동합니다.
— Almino Melo

6
동적로드 테이블의 경우 : $('body') .on('show.bs.dropdown', '.table-responsive', function () { $(this).css("overflow", "visible"); }) .on('hide.bs.dropdown', '.table-responsive', function () { $(this).css("overflow", "auto"); });
— Exlord

4
그러나 클릭 후 데이터는 화면의 최소 크기를 벗어납니다. 그래서 이것은 작동하지 않습니다. !!!!
— Shreya Shah

1
드롭 다운이 열릴 때 테이블이 왼쪽으로 다시 스크롤되는 것을 막을 수 있다면 작동합니다. 그러나 화면 오른쪽에 드롭 다운이있는 경우 테이블을 열 때 왼쪽으로 이동합니다. 가장 오른쪽에있는 드롭 다운 ( .table-responsive클래스에 의해 마스킹 됨 )은 편집하려고 할 때 완전히 숨겨집니다.
— Ponyboy

43

CSS 유일한 해결책은 오버플로 y 축을 허용한다.

http://www.bootply.com/YvePJTDzI0

.table-responsive {
  overflow-y: visible !important;
}

편집하다

또 다른 CSS 유일한 해결책은 뷰포트 너비에 따라 오버플로를 반응 적으로 적용하는 것입니다.

@media (max-width: 767px) {
    .table-responsive .dropdown-menu {
        position: static !important;
    }
}
@media (min-width: 768px) {
    .table-responsive {
        overflow: inherit;
    }
}

https://www.codeply.com/go/D3XBvspns4


@ZimSystem 여전히 똑같은 일을하지만 이것은 근본적으로 해결책이 아닙니다.
— Jemar Jones

이 솔루션은 사용자 지정 CSS를 제거하더라도 작동합니다. 아마도 html 일 것입니다. 나는 여전히 CSS 전용 솔루션을 찾고 있습니다.
— 페르난도

1
아뇨. 작동하지 않습니다. 나는 데이터 테이블을 사용하고 있기 때문에 것 같아요
— peterchaula

버튼을 제외하고 나를 위해 작품 다음 드롭 다운 ... 창 밖에서 나타납니다 ... 페이지 하단에
— 브루 알파

34

참고로 2018 년이고 BS4.1을 사용하고 있습니다.

data-boundary="viewport"드롭 다운을 토글하는 버튼 (클래스가있는 버튼)에 추가해보세요 dropdown-toggle. https://getbootstrap.com/docs/4.1/components/dropdowns/#options를 참조 하십시오.


4
나는 이것이 내가 생각해 낸 작업 솔루션임을 확인합니다.
— sdvnksv

4
이전 버전에 대해서는 말할 수 없지만 Bootstrap 4의 경우 이것이 실제로 최상의 솔루션입니다. 간단하고, 응답 성을 희생하지 않으며, 추가 스타일이나 스크립트로 해킹하려고하는 대신 프레임 워크에 이미 제공된 기능을 사용합니다.
— T. Linnell

16

나는 다른 접근 방식을 취했고 부모에서 요소를 분리하고 jQuery에 의해 절대 위치로 설정했습니다.

작동하는 JS 파일 : http://jsfiddle.net/s270Lyrd/

여기에 이미지 설명 입력

내가 사용하고있는 JS 솔루션.

//fix menu overflow under the responsive table 
// hide menu on click... (This is a must because when we open a menu )
$(document).click(function (event) {
    //hide all our dropdowns
    $('.dropdown-menu[data-parent]').hide();

});
$(document).on('click', '.table-responsive [data-toggle="dropdown"]', function () {
    // if the button is inside a modal
    if ($('body').hasClass('modal-open')) {
        throw new Error("This solution is not working inside a responsive table inside a modal, you need to find out a way to calculate the modal Z-index and add it to the element")
        return true;
    }

    $buttonGroup = $(this).parent();
    if (!$buttonGroup.attr('data-attachedUl')) {
        var ts = +new Date;
        $ul = $(this).siblings('ul');
        $ul.attr('data-parent', ts);
        $buttonGroup.attr('data-attachedUl', ts);
        $(window).resize(function () {
            $ul.css('display', 'none').data('top');
        });
    } else {
        $ul = $('[data-parent=' + $buttonGroup.attr('data-attachedUl') + ']');
    }
    if (!$buttonGroup.hasClass('open')) {
        $ul.css('display', 'none');
        return;
    }
    dropDownFixPosition($(this).parent(), $ul);
    function dropDownFixPosition(button, dropdown) {
        var dropDownTop = button.offset().top + button.outerHeight();
        dropdown.css('top', dropDownTop + "px");
        dropdown.css('left', button.offset().left + "px");
        dropdown.css('position', "absolute");

        dropdown.css('width', dropdown.width());
        dropdown.css('heigt', dropdown.height());
        dropdown.css('display', 'block');
        dropdown.appendTo('body');
    }
});

1
이 답변은 jquery datatable (ajax render)을 사용하는 동안 저에게 완벽한 수정입니다. 나는 그에 따라 조정했고 훌륭하게 작동합니다.


11

내 2 ¢ 빠른 글로벌 수정 :

// drop down in responsive table

(function () {
  $('.table-responsive').on('shown.bs.dropdown', function (e) {
    var $table = $(this),
        $menu = $(e.target).find('.dropdown-menu'),
        tableOffsetHeight = $table.offset().top + $table.height(),
        menuOffsetHeight = $menu.offset().top + $menu.outerHeight(true);

    if (menuOffsetHeight > tableOffsetHeight)
      $table.css("padding-bottom", menuOffsetHeight - tableOffsetHeight);
  });

  $('.table-responsive').on('hide.bs.dropdown', function () {
    $(this).css("padding-bottom", 0);
  })
})();

설명 : '.table-responsive'내에 드롭 다운 메뉴가 표시되면 테이블의 높이를 계산하고 메뉴를 표시하는 데 필요한 높이와 일치하도록 확장 (패딩 포함)합니다. 메뉴는 모든 크기가 될 수 있습니다.

제 경우에는 '.table-responsive'클래스가있는 테이블이 아니라 래핑 div입니다.

<div class="table-responsive" style="overflow:auto;">
    <table class="table table-hover table-bordered table-condensed server-sort">

따라서 스크립트의 $ table var는 실제로 div입니다! (단지 명확하게 ... 또는 아닙니다) :)

참고 : IDE에서 함수를 축소 할 수 있도록 함수로 래핑하지만 필수는 아닙니다!


2
이것은 나를 위해 일한 유일한 솔루션이지만 $ table.css ( "padding-bottom", menuOffsetHeight-tableOffsetHeight + 16); $ table.css ( "padding-bottom", menuOffsetHeight-tableOffsetHeight); 기본적으로 부트 스트랩에있는 추가 패딩과 하단에 작은 간격을 추가합니다.
— 필 젊은

이것은 작동하지만 패딩으로 인해 나빠 보입니다. 패딩 팽창없이 작동하도록 만든 솔루션이 있었으면합니다.
— Qasim

좋은 간단한 솔루션
— NMC

11

CSS 만 사용하는 솔루션이 있으며 테이블 응답 내부의 드롭 다운에 대해 위치 상대를 사용하십시오.

@media (max-width: 767px) {
  .table-responsive .dropdown-menu {
    position: relative; /* Sometimes needs !important */
  }
}

https://codepen.io/leocaseiro/full/rKxmpz/


1
이것이 최선의 해결책이며 반응 형 테이블에서 ui-select에 사용하고 있습니다.
— Sergio Ivanuzzo

나에게도 최고의 솔루션
— Mauro

2
이 바이올린은 작동하지 않습니다 . 그것은 숨어 유지 테이블 아래에있는 드롭 다운을.
— HelloIT

codepen (업데이트)하려고 @HelloIT codepen.io/leocaseiro/pen/rKxmpz
— 레오 Caseiro

1
이 방법은 펜으로 작동하는 표시되지 않습니다 @hellioIT에 동의
— MrPaulDriver


6

이것은 Bootstrap v4.1 이상에서 data-boundary="viewport"( Bootstrap Dropdowns Docs )를

하지만 이전 버전 (v4.0 이하)의 경우 완벽하게 작동하는 이 자바 스크립트 스 니펫 을 찾았습니다 . 작은 테이블과 스크롤 테이블에서 작동합니다.

$('.table-responsive').on('shown.bs.dropdown', function (e) {
    var t = $(this),
        m = $(e.target).find('.dropdown-menu'),
        tb = t.offset().top + t.height(),
        mb = m.offset().top + m.outerHeight(true),
        d = 20; // Space for shadow + scrollbar.
    if (t[0].scrollWidth > t.innerWidth()) {
        if (mb + d > tb) {
            t.css('padding-bottom', ((mb + d) - tb));
        }
    }
    else {
        t.css('overflow', 'visible');
    }
}).on('hidden.bs.dropdown', function () {
    $(this).css({'padding-bottom': '', 'overflow': ''});
});

4

@Wazime 솔루션을 약간 정리했습니다. 일반적인 솔루션으로 훌륭하게 작동합니다.

$(document).on('shown.bs.dropdown', '.table-responsive', function (e) {
    // The .dropdown container
    var $container = $(e.target);

    // Find the actual .dropdown-menu
    var $dropdown = $container.find('.dropdown-menu');
    if ($dropdown.length) {
        // Save a reference to it, so we can find it after we've attached it to the body
        $container.data('dropdown-menu', $dropdown);
    } else {
        $dropdown = $container.data('dropdown-menu');
    }

    $dropdown.css('top', ($container.offset().top + $container.outerHeight()) + 'px');
    $dropdown.css('left', $container.offset().left + 'px');
    $dropdown.css('position', 'absolute');
    $dropdown.css('display', 'block');
    $dropdown.appendTo('body');
});

$(document).on('hide.bs.dropdown', '.table-responsive', function (e) {
    // Hide the dropdown menu bound to this button
    $(e.target).data('dropdown-menu').css('display', 'none');
});

2

권장되고 선택한 솔루션이 항상 최상의 솔루션은 아닙니다. 불행히도 그 솔루션은 최근에 사용되었으며 상황에 따라 페이지에 여러 스크롤바를 만듭니다.

제 방법은 약간 달랐습니다.

다른 div에 테이블 응답 div를 포함했습니다. 그런 다음 높이와 너비가 페이지 크기를 기반으로하도록 높이 100 %, 너비 : 100 %, 디스플레이 블록 및 위치 절대를 적용하고 오버플로를 숨김으로 설정했습니다.

그런 다음 테이블 반응 형 div에 최소 높이를 100 % 추가했습니다.

<div class="table_container" 
    style="height: 100%; width: 100%; display: block;position: absolute;overflow: hidden;">
<div class="table-responsive" style="min-height:100%;">

아래의 작업 예제에서 볼 수 있듯이 스크롤 막대가 추가되지 않았고 재미있는 동작이 없으며 실제로 사용 비율로 표시됩니다. 화면 크기에 관계없이 작동해야합니다. 그러나 나는 이것을 테스트하지 않았습니다. 어떤 이유로 실패하면 100 %를 각각 100vh 및 100vw로 대체 할 수 있습니다.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

            <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


<div class="table_container" style="height: 100%; width: 100%; display: block;position: absolute;overflow: hidden;">
<div class="table-responsive" style="min-height:100%;">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Value1</th>
                            <th>Value2</th>
                            <th>Value3</th>
                            <th>Value4</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>
                                DATA
                                <div class="btn-group btn-group-rounded">
                                    <button type="button" class="btn btn-default btn-xs" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-radius:3px;">
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">One</a></li>
                                        <li><a href="#">Two</a></li>
                                        <li><a href="#">Three</a></li>
                                        <li role="seperator" class="divider"></li>
                                        <li><a href="#">Four</a></li>
                                    </ul>
                                </div>
                            </td>

                            <td>
                                DATA
                                <div class="btn-group btn-group-rounded">
                                    <button type="button" class="btn btn-default btn-xs" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-radius:3px;">
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">One</a></li>
                                        <li><a href="#">Two</a></li>
                                        <li><a href="#">Three</a></li>
                                        <li role="seperator" class="divider"></li>
                                        <li><a href="#">Four</a></li>
                                    </ul>
                                </div>
                            </td>
                            <td>
                                DATA
                                <div class="btn-group btn-group-rounded">
                                    <button type="button" class="btn btn-default btn-xs" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-radius:3px;">
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">One</a></li>
                                        <li><a href="#">Two</a></li>
                                        <li><a href="#">Three</a></li>
                                        <li role="seperator" class="divider"></li>
                                        <li><a href="#">Four</a></li>
                                    </ul>
                                </div>
                            </td>
                            <td>DATA</td>
                        </tr>
                        <tr>
                            <td>
                                DATA
                                <div class="btn-group btn-group-rounded">
                                    <button type="button" class="btn btn-default btn-xs" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-radius:3px;">
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">One</a></li>
                                        <li><a href="#">Two</a></li>
                                        <li><a href="#">Three</a></li>
                                        <li role="seperator" class="divider"></li>
                                        <li><a href="#">Four</a></li>                                    </ul>
                                </div>
                            </td>

                            <td>
                                DATA
                                <div class="btn-group btn-group-rounded">
                                    <button type="button" class="btn btn-default btn-xs" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-radius:3px;">
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">One</a></li>
                                        <li><a href="#">Two</a></li>
                                        <li><a href="#">Three</a></li>
                                        <li role="seperator" class="divider"></li>
                                        <li><a href="#">Four</a></li>
                                    </ul>
                                </div>
                            </td>
                            <td>
                                DATA
                                <div class="btn-group btn-group-rounded">
                                    <button type="button" class="btn btn-default btn-xs" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="border-radius:3px;">
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a href="#">One</a></li>
                                        <li><a href="#">Two</a></li>
                                        <li><a href="#">Three</a></li>
                                        <li role="seperator" class="divider"></li>
                                        <li><a href="#">Four</a></li>
                                    </ul>
                                </div>
                            </td>
                            <td>DATA</td>
                        </tr>
                    </tbody>
                </table>
            </div>
</div>


더 작은 뷰 높이에 대한 솔루션이 아닙니다. 보기에서 벗어 났기 때문에 하단 드롭 다운 링크에 더 이상 연결할 수 없습니다.
— Seika85

1

받아 들여진 대답과 @LeoCaseiro의 대답을 바탕으로 내 경우에 사용하게 된 것입니다.

@media (max-width: 767px) {
    .table-responsive{
        overflow-x: auto;
        overflow-y: auto;
    }
}
@media (min-width: 767px) {
    .table-responsive{
        overflow: inherit !important; /* Sometimes needs !important */
    }
}

큰 화면에서는 드롭 다운이 반응 형 테이블 뒤에 숨겨지지 않고 작은 화면에서는 숨겨 지지만 어쨌든 모바일에는 스크롤 막대가 있으므로 괜찮습니다.

이것이 누군가를 돕기를 바랍니다.


0

Burebistaruler 응답은 ios8 (iphone4s)에서는 잘 작동하지만 이전에 작동하던 Android에서는 작동하지 않습니다. ios8 (iphone4s) 및 andoir에서 나를 위해 작동하는 것은 다음과 같습니다.

$('.table-responsive').on('show.bs.dropdown', function () {
 $('.table-responsive').css( "min-height", "400px" );
});

$('.table-responsive').on('hide.bs.dropdown', function () {
     $('.table-responsive').css( "min-height", "none" );
})

0

이것은 다른 사람에게 유용 할 수 있습니다. DatatablesJS를 사용하고 있습니다. 테이블의 현재 높이에 500px를 추가합니다. Datatables를 사용하면 테이블에서 10, 20 등의 페이지를 사용할 수 있기 때문에 이렇게합니다. 따라서 테이블의 높이를 다이너 믹하게 계산해야합니다.
드롭 다운이 표시되면 높이를 추가합니다.
드롭 다운이 숨겨지면 원래 테이블의 높이를 재설정합니다.

$(document).ready(function() {
    $('.table-responsive .dropdown').on('shown.bs.dropdown', function () {
          console.log($('#table-responsive-cliente').height() + 500)
          $("#table-responsive-cliente").css("height",$('#table-responsive-cliente').height() + 500 );
    })

    $('.table-responsive .dropdown').on('hide.bs.dropdown', function () {
           $("#table-responsive-cliente").css("height","auto");
    })
})

그리고 HTML

<div class="table-responsive" id="table-responsive-cliente">
    <table class="table-striped table-hover">
     ....

     ....
    </table>
</div>

전에: 여기에 이미지 설명 입력

드롭 다운이 표시된 후 : 여기에 이미지 설명 입력


0

드롭 다운이 테이블 하단에 가까울 때 드롭 다운에 .dropup 클래스를 적용하여 직장에서이 문제를 해결했습니다. 여기에 이미지 설명 입력


결국 그 솔루션에 가장 만족합니다. $('table tr:nth-last-child(-n+3) td').addClass('dropup').
— Furgas

0

이것은 v3와 다른 중단 점이 있기 때문에 Bootstrap 4에서 저에게 효과적이었습니다.

@media (min-width: 992px) {
    .table-responsive {
        overflow: inherit;
    }
}

0

사람들이 여전히이 문제에 갇혀 있고 우리가 이미 2020 년에있는 한. 드롭 다운 메뉴에 플렉스 디스플레이를 제공하여 순수한 CSS 솔루션을 얻습니다.

이 스 니펫은 datatable-scroll-wrap수업에서 잘 작동합니다.

.datatable-scroll-wrap .dropdown.dropup.open .dropdown-menu {
    display: flex;
}
.datatable-scroll-wrap .dropdown.dropup.open .dropdown-menu li a {
    display: flex;
}

0

글쎄, 최고 답변을 읽으면 스크롤 막대를 볼 때 토글 버튼이 마지막 열 (내 경우) 또는 보이지 않는 다른 열에있을 때 실제로 작동하지 않는다는 것을 알았습니다.

그림 오류

그러나 '상속'을 '숨김'으로 변경하면 작동합니다.

$('.table-responsive').on('show.bs.dropdown', function () {
    $('.table-responsive').css( "overflow", "hidden" );
}).on('hide.bs.dropdown', function () {
    $('.table-responsive').css( "overflow", "auto" );
})

여기에 이미지 설명 입력

그렇게 해보십시오.


0

한 번 시도하십시오. 인터넷에서 1 시간 동안 조사한 후이 문제에 대한 최상의 솔루션을 찾았습니다.

해결책 :- 그냥 스크립트 추가

(function () {
    // hold onto the drop down menu                                             
    var dropdownMenu;

    // and when you show it, move it to the body                                     
    $(window).on('show.bs.dropdown', function (e) {

    // grab the menu        
    dropdownMenu = $(e.target).find('.dropdown-menu');

    // detach it and append it to the body
    $('body').append(dropdownMenu.detach());

    // grab the new offset position
    var eOffset = $(e.target).offset();

    // make sure to place it where it would normally go (this could be improved)
    dropdownMenu.css({
        'display': 'block',
            'top': eOffset.top + $(e.target).outerHeight(),
            'left': eOffset.left
       });
    });

    // and when you hide it, reattach the drop down, and hide it normally                                                   
    $(window).on('hide.bs.dropdown', function (e) {
        $(e.target).append(dropdownMenu.detach());
        dropdownMenu.hide();
    });
})();

산출:- 해결책


-1

bootstrap.css 내부에서 다음 코드를 검색합니다.

.fixed-table-body {
  overflow-x: auto;
  overflow-y: auto;
  height: 100%;
}

... 다음으로 업데이트하십시오.

.fixed-table-body {
  overflow-x: visible;
  overflow-y: visible;
  height: 100%;
}

-1

이것을 사용하십시오

.table-responsive {
    overflow: inherit;
}

Chrome에서는 작동하지만 상속 속성이 지원되지 않으므로 IE10 또는 Edge에서는 작동하지 않습니다.


-2

제 경우에는 잘 작동합니다.

.table-responsive {
  overflow-y: visible !important;
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.