Stop just one dropdown toggle from closing on click

前端 未结 7 2195
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 08:58

I have a button dropdown (just one, not all of them), and inside of it, I want to have several input field where people can type stuff inside without the dropdown hiding as

相关标签:
7条回答
  • 2020-12-13 09:08

    Actually, if you were in Angular.js, it would be more elegant to make a directive for it:

    app.directive('stopClickPropagation', function() {
        return {
            restrict: 'A',
            link: function(scope, element) {
                element.click(function(e) {
                    e.stopPropagation();
                });
            }
        };
    });
    

    And then, on the dropdown-menu, add the directive:

    <div class="dropdown-menu" stop-click-propagation> 
        my dropdown content...
    <div>
    

    Especially if you want to stop propagation for multiple mouse events:

    ...
    element.click(function(e) {
        e.stopPropagation();
    });
    
    element.mousedown(...
    element.mouseup(...
    ...
    
    0 讨论(0)
  • 2020-12-13 09:19

    also, prevent click unless clicks a button element

    $('.dropdown-menu').click(function(e) {
        if (e.target.nodeName !== 'BUTTON') e.stopPropagation();
    });
    
    0 讨论(0)
  • 2020-12-13 09:21

    The issue is that the boostrap dropdown jQuery plugin closes the dropped-menu when you click anywhere else. You can disable that behavior by capturing the click events on your dropdown-menu element and keeping it from reaching the click event listeners on the body element.

    Just add

    $('.dropdown-menu').click(function(event){
         event.stopPropagation();
     });​
    

    jsfiddle can be found here

    0 讨论(0)
  • I know this question isn't for Angular per se, but for anyone using Angular you can pass the event from the HTML and stop propagation via $event:

    <div ng-click="$event.stopPropagation();">
        <span>Content example</span>
    </div>
    
    0 讨论(0)
  • 2020-12-13 09:29

    After trying a lot of techniques I found that the best one to use, that causes no drawbacks which is even simple:

    $(document)
    .on( 'click', '.dropdown-menu', function (e){
        e.stopPropagation();
    });
    

    Which lets you also do some live binding for inner elements inside dropdowns.

    0 讨论(0)
  • 2020-12-13 09:31

    Another quick solution, just add onclick attribute to div having class dropdown-menu:

    <div class="dropdown-menu" onClick="event.stopPropagation();">...</div>
    
    0 讨论(0)
提交回复
热议问题