使用表格内的按钮打开引导下拉菜单
function xonclick() {
new bootstrap.Popover(
document.getElementById("grid_muu"),
document.getElementById("seadedMenyy"), {
placement: "auto"
},
)
document.getElementById("settingsDropDown").click()
}
#settingsDropDown {
display: none;
}
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="dropdown">
<button id="settingsDropDown" class="btn" type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown button
</button>
<ul class="dropdown-menu" id="seadedMenyy">
<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>
<table>
<tr>
<td>Some text</td>
<td><button onclick="xonclick()" id="grid_muu">
Open menu</button></td>
</tr>
</table>
</body>
打不开它。单击“打开菜单”按钮不会执行任何操作。 如果单击按钮,如何打开该按钮附近的下拉菜单?
Dropdown 在 DOM 中的其他位置定义,并且 display 设置为 none。
我认为你需要使用
bootstrap.Dropdown
而不是 bootstrap.Popover
。
单击按钮附近的下拉菜单位置错误。
正确的代码如下:
function xonclick() {
const dropdownButton = document.getElementById('settingsDropDown');
const dropdownMenu = document.getElementById('seadedMenyy');
// Position the dropdown near the clicked button
const clickedButton = document.getElementById('grid_muu');
const buttonRect = clickedButton.getBoundingClientRect();
dropdownMenu.style.position = 'absolute';
dropdownMenu.style.left = buttonRect.left + 'px';
dropdownMenu.style.top = (buttonRect.bottom + 2) + 'px';
// Create and show dropdown
const dropdown = new bootstrap.Dropdown(dropdownButton);
dropdown.show();
}
.
#settingsDropDown {
position: absolute;
visibility: hidden;
pointer-events: none;
}
.dropdown-menu {
display: block;
opacity: 0;
transition: opacity 0.2s;
}
.dropdown-menu.show {
opacity: 1;
}
.
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="dropdown">
<button id="settingsDropDown" class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown button
</button>
<ul class="dropdown-menu" id="seadedMenyy">
<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>
<table>
<tr>
<td>Some text</td>
<td><button id="grid_muu" onclick="xonclick()">Open menu</button></td>
</tr>
</table>
</body>
您现在可以单击“打开菜单”btn,下拉菜单将出现在其正下方,同时隐藏实际的下拉菜单触发器 btn。 谢谢