简体   繁体   中英

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

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

For instance, I have a button at the top of the page special menu , and one in the middle special menu ... and another at the bottom special menu . When any of them is clicked, it should open a drop-down (or popover) nearby. Not just nearby the first special menu . But near by the clicked one.

The dropdown should be the same html element . Not html copies. Not on-the-fly copies. Not a copy at all. Just one element.

Just one copy that could be opened and displayed near by the buttons from which it has been opened.

I have found nothing using bootstrap, and have not been successful at all with Popper.js (even if I guess it might be a solution).

Assuming you've created the dropdown element:

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

or grabbed in from the DOM:

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

You could take an approach like this:

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]);
}

Of course, the exact implementation depends on how you want the DOM set up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM