programing

스크롤로 인해 응답 테이블 내부의 부트스트랩 버튼 드롭다운이 표시되지 않음

telebox 2023. 8. 15. 11:02
반응형

스크롤로 인해 응답 테이블 내부의 부트스트랩 버튼 드롭다운이 표시되지 않음

다음과 같은 이유로 드롭다운이 보이지 않기 때문에 응답이 있고 스크롤이 활성화되어 있을 때 테이블 내부의 드롭다운 버튼에 문제가 있습니다.overflow: auto; 옵션을 해야 ?접혔을 때 버튼의 드롭다운 옵션을 표시하려면 어떻게 해야 합니까?저는 jQuery를 사용할 수 있지만 좌우 스크롤에 문제가 생긴 후 다른 해결책을 찾기로 했습니다.더 잘 이해하기 위해 사진을 첨부했습니다.enter image description here

여기 작은 js 바이올린이 있습니다.

저는 이 문제를 해결하고 동일한 문제가 있는 다른 사용자를 돕기 위해 답을 제시했습니다.부트스트랩에 이벤트가 있고 그 이벤트를 사용하여 설정할 수 있습니다.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:이 바이올린 예제에서는 이상하게 작동하고 왜 그런지는 모르겠지만 제 프로젝트에서는 잘 작동합니다.

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

추가시를 추가해 .data-boundary="viewport"(클래스가 " " " (으)로 되는" dropdown-toggle. https://getbootstrap.com/docs/4.1/components/dropdowns/ #http://# 를 참조하십시오.

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

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

작업 JS 피들: http://jsfiddle.net/s270Lyrd/

enter image description here

제가 사용하고 있는 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');
    }
});

이 솔루션은 저에게 매우 효과적이었습니다.

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

자세한 정보: https://github.com/twbs/bootstrap/issues/15374

부트스트랩 5 솔루션

이것이 저에게 가장 효과적인 방법입니다.

.table-responsive .dropdown,
.table-responsive .btn-group,
.table-responsive .btn-group-vertical {
    position: static;
}

이 속성을 정의합니다.행운을 빕니다.

data-toggle="dropdown" data-boundary="window"

나의 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-response' 클래스를 가진 테이블이 아니라 래핑 디브입니다.

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

그래서 스크립트의 $table var는 사실 div입니다! (분명히 말하자면...아님 아님) :)

참고: IDE가 함수를 접을 수 있도록 함수로 포장합니다 ;) 하지만 필수는 아닙니다!

CSS만 사용하는 솔루션이 있습니다. 테이블 내 드롭다운에 상대적인 위치를 사용하십시오. 응답:

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

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

v4에서 이문제부랩v4.1 상서다추를 하여 되었습니다.data-boundary="viewport"(부팅스트랩 드롭다운 문서)

그러나 이전 버전(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': ''});
});

번 시도해 보세요. 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();
    });
})();

출력:- Solution

@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');
});

SIMPLE CSS 전용 솔루션

Rather than modifying the parent table, Here I have a simple solution

는 z-index에 입니다.<td></td>당신의 드롭다운을 유지합니다.그래서 그것은 다른 모든 요소들 위에 있을 것입니다.

<td style="position: absolute; z-index: 10; width: 20%;"></td>

뷰레비스타룰러 응답은 ios8(iphone4s)에서는 잘 작동하지만 이전에 작동했던 안드로이드에서는 작동하지 않습니다.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" );
})

@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 */
    }
}

큰 화면에서는 드롭다운이 응답 테이블 뒤에 숨겨져 있지 않고 작은 화면에서는 숨겨지지만 모바일에는 스크롤 막대가 있기 때문에 괜찮습니다.

이것이 누군가에게 도움이 되기를 바랍니다.

권장되고 선택된 솔루션이 항상 최선의 솔루션은 아닙니다.안타깝게도 최근에 사용된 솔루션 링크드인은 상황에 따라 페이지에 여러 개의 스크롤바를 만듭니다.

제 방법은 조금 달랐습니다.

저는 테이블에 반응하는 디브를 다른 디브에 포함시켰습니다.그런 다음 높이 100%, 너비 100%, 디스플레이 블록과 위치 절대값을 적용하여 높이와 너비가 페이지 크기를 기준으로 하고 오버플로를 숨김으로 설정했습니다.

그런 다음 테이블에 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>

또 다른 해결책은

.table-responsive{
  min-height: 400px;
}

저는 몇 가지 조사를 해봤지만 모든 답이 저를 위해 그것을 해결해주지는 못했지만, 그들은 저를 올바른 방향으로 인도해주었습니다.

경계가 이미 "창"으로 설정되었습니다.

나의<tbody>가 있었습니다.position: relative;드롭다운 메뉴에는 다음이 있습니다.position: absolute;하지만 문제를 일으킨 t 본체에 "부드럽게" 유지했습니다.

변경했습니다.<tbody>position: static;자바스크립트 없이 내 문제를 해결했고, 테이블은 여전히 응답합니다.


그나저나 저는 부트스트랩 4를 사용하고 있습니다.

글로벌 CSS 규칙을 변경하지 않은 나의 간단한 JS 솔루션.

참고: '.table-scrollable'을 '.table-responsive'로 대체해야 할 수 있습니다.

$('.table-scrollable').on('show.bs.dropdown', function (e) {
        //get button position
        offset = $(e.relatedTarget).offset() 

        //get button height
        heigth = $(e.relatedTarget).outerHeight()

        //append dropdown to body and perpare position.
        $(e.relatedTarget).next('.dropdown-menu').addClass('dropdown-menu-in-table').appendTo("body").css({display:'block',top:offset.top+heigth, left: offset.left});
});

//move back dropdown menu to button and remove positon
$('body').on('hide.bs.dropdown', function (e) {                                    
        $(this).find('.dropdown-menu-in-table').removeClass('dropdown-menu-in-table').css({display:'',top:'', left: ''}).appendTo($(e.relatedTarget).parent());
});

저의 해결책은 다음과 같습니다.

.table-responsive {
    min-height: 300px;
}

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

이것은 다른 사람에게 유용할 수 있습니다.데이터 테이블을 사용하고 있습니다.JS. 테이블의 현재 높이에 500px를 추가합니다.데이터 테이블을 사용하면 테이블에서 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>

이전:

드롭다운이 표시된 후:

드롭다운이 테이블의 맨 아래에 가까울 때 드롭다운에 .dropup 클래스를 적용하여 이 문제를 해결했습니다. 여기에 이미지 설명을 입력하십시오.

부트스트랩 4는 v3와 다른 중단점을 가지고 있기 때문에 저에게 효과가 있었습니다.

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

글쎄요, 상단 답변을 읽었을 때, 스크롤 막대를 보고 있을 때 토글 버튼이 마지막 열(나의 경우) 또는 보이지 않는 다른 열에 있을 때 정말 작동하지 않는다는 것을 알았습니다.

pic-error

그러나 'hidden'을 'hidden'으로 변경하면 작동합니다.

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

enter image description here

그렇게 해보세요.

Bootstrap 5.2를 사용하여 응답성이 필요한 큰 테이블을 최근 Github(Nov 2022)게시한 이 솔루션은 저에게 탁월하게 효과가 있었습니다.

드롭다운을 처음 렌더링한 후 다음 자바스크립트를 호출합니다(Blazor Server).

const dropdowns = document.querySelectorAll('.dropdown-toggle')
const dropdown = [...dropdowns].map((dropdownToggleEl) => new bootstrap.Dropdown(dropdownToggleEl, {
    popperConfig(defaultBsPopperConfig) {
        return { ...defaultBsPopperConfig, strategy: 'fixed' };
    }
}));

드롭다운은 이제 테이블의 수직 크기나 분할에 영향을 주지 않고 테이블 응답 래퍼 외부로 확장할 수 있으며 큰 화면과 작은 화면 모두에서 작동합니다.

에 관한 나의 경우에는boostrap vue와 함께v-select inside inline-edit table나는 ...에 의해 해결되었습니다.

<style lang="scss" scoped>
...
...
.custom-yo-select >>> .vs__dropdown-menu {
                max-height: 13em !important;
                position: relative !important;
                font-weight: 700 !important;
              }
              .custom-yo-select::v-deep .vs__dropdown-menu {
                max-height: 13em !important;
                position: relative !important;
                font-weight: 700 !important;
              }

여기 코드가 있습니다.

<v-select
                    v-if="
                      ['select'].includes(data.field.input.type) &&
                      'columnKey' in data.field
                    "
                    v-model="
                      data.item[data.field.key.toString().split('.')[0]][
                        data.field.key.toString().split('.')[1]
                      ]
                    "
                    class="custom-yo-select" // put the scss
                    :disabled="data.field.input.disabled"
                    :state="
                      data.field.columnKey === 'dm_master' &&
                      data.item[data.field.columnKey || data.field.key] === 0
                        ? false
                        : data.field.input.options && data.field.input.boolean
                        ? true
                        : true
                    "
                    :dir="$store.state.appConfig.isRTL ? 'rtl' : 'ltr'"
                    :options="selectModal.options"
                    @keyup.enter.shift.exact="showSelectModal(data)"
                    @keyup.enter.ctrl.exact="showSelectModal(data)"
                    @input="showSelectModal(data)"
                    @search:focus="showSelectModal(data)"
                    @search:blur="showSelectModal(data)"
                  >
"bootstrap": "4.6.0",
"bootstrap-vue": "2.21.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%;
}

간단히 사용

.table-responsive {
    overflow: inherit;
}

Chrome에서는 작동하지만 상속 속성이 지원되지 않기 때문에 IE10 또는 Edge에서는 작동하지 않습니다.

저의 경우, 이것은 잘 작동합니다.

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

사람들이 여전히 이 문제에 갇혀 있고 우리가 이미 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;
}

언급URL : https://stackoverflow.com/questions/26018756/bootstrap-button-drop-down-inside-responsive-table-not-visible-because-of-scroll

반응형