Bootstrap 引导下拉菜单-通过外部按钮触发

mklgxw1f  于 2023-09-28  发布在  Bootstrap
关注(0)|答案(1)|浏览(155)

我正在使用Bootstrap 5下拉列表。我需要的按钮,触发下拉打开活的父元素(下)。如何使用Jquery或JS?

<div class="A"> 
    <!-- need button to live here -->
</div>

<div class="B">
    <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown button </button>
    <div class="dropdown">
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
        </ul>
    </div>
</div>
vcirk6k6

vcirk6k61#

你不能用attribute来做,但是你可以用jquery来控制下拉列表,例如:
网址:

<div class="A"> 
    <button class="btn btn-secondary" data-dropdown-target="#dropdown1" type="button" aria-expanded="false"></button>
</div>
<div class="B">
    <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown button </button>
    <div class="dropdown" id="dropdown1">
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
        </ul>
    </div>
</div>

js:

$('[data-dropdown-target]').on('click', function() {
    $($(this).attr('data-dropdown-target')).dropdown('toggle');
});

如果你想使用像默认按钮一样的按钮,包括点击外部的关闭事件...,你可以使用这个:

$(document).on('click', function (e) {
    $target = $(e.target);
    $('.dropdown.show').each((i, el) => {
        if(
            !$($target).closest('[data-dropdown-target="#'+$(el).attr('id')+'"]').length &&
            $('[data-dropdown-target="#'+$(el).attr('id')+'"]').length !== 0 &&
            $target !== $(el) &&
            !$($target).closest(el).length
        ) {
            $(el).dropdown('hide');
        }
    });
});

相关问题