Dynamically add a class to Bootstrap's 'popover' container

后端 未结 22 2570
名媛妹妹
名媛妹妹 2020-11-29 18:27

I\'ve thoroughly searched through both StackOverflow and Google, but come up empty. So apologies in advance if this has been asked & resolved already.

NB

22条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 19:06

    I know this thread is old, but for those who stumble across this article as I did, here is another method that will allow more customisation. I haven't tested it with Bootstrap 4 but it with Bootstrap 3.

    Instead of hard-coding a class in the function, you can 'submit' a css class to your popover via your html element using a custom data attribute. For this example I've called that attribute "data-class".

    As this method exploits the function available to the popovers 'placement' options, I've configured it to preserve the original placement configured in the popover.

    jQuery( '[data-toggle="popover"]' ).popover({
    
        container: 'body',
    
        placement: function ( popover, trigger ){
    
            // Get the submitted placement for the popover
            var placement = jQuery( trigger ).attr( 'data-placement' );
    
            // Get the class(es) to apply to the popover
            var dataClass = jQuery( trigger ).attr( 'data-class' );
    
            // Apply the submitted class(es) to the popover element
            jQuery( popover).addClass( dataClass );
    
            // Return the original placement for the popover
            return placement;
    
            },
    
            trigger: 'hover'
    
    });
    

    I hope this helps. If anyone has a better or cleaner way of doing this I'd be happy to learn :)

提交回复
热议问题