如何用多个按钮触发相同的drop-down/popover?

How to trigger the same drop-down/popover with multiple buttons?

如何用多个按钮触发同一个下拉菜单?

例如,我在页面顶部有一个按钮 special menu,在中间有一个按钮 special menu... 另一个在底部 special menu。单击其中任何一个时,它应该会在附近打开一个下拉菜单(或弹出窗口)。不只是在第一个 special menu 附近。但在点击的附近。

下拉菜单应该是 相同的 html 元素。不是 html 份。不是即时副本。根本不是副本。只有一个元素。

只有一个副本可以打开并显示在打开它的按钮附近。

我在使用 bootstrap 时一无所获,并且在使用 Popper.js 时完全没有成功(即使我猜它可能是一个解决方案)。

假设您已经创建了下拉元素:

var dropdown = document.createElement('div');
//  TODO: Populate the element.

或从 DOM 抓取:

var dropdown = document.getElementById('dropdown');

您可以采用这样的方法:

function attachListener(target) {
    target.addEventListener('click', function() {
        if (dropdown.parentNode) {
            //  Remove dropdown from the DOM.
            dropdown.parentNode.removeChild(dropdown);
        }

        //  Add the dropdown inside the target.
        target.appendChild(dropdown);
    });
}

var targets = document.getElementsByClassName('special-menu');
for (var i = 0; i < targets.length; i++) {
    attachListener(targets[i]);
}

当然,具体的实施取决于您希望如何设置 DOM。