问题
I have a navbar with dropdowns that work perfectly with hover. But on smartphones, instead of tapping to open the dropdown, I want it to open automatically as soon as the toggle menu button is tapped.
I've tried some snippets I've found around here but haven't managed to adapt any to my problem.
回答1:
Just manually add the class "in" to the element with the collapse navbar-collapse classes in your markup.
<nav class="collapse navbar-collapse in" role="navigation">
From the Bootstrap documentation on the Collapse plugin:
Be sure to add the class collapse to the collapsible element. If you'd like it to default open, add the additional class in.
EDIT:
Sorry, I misread the question. Here is a DEMO.
To open the submenus, @scooterlord is correct, but the trick is that you need to use the right event. If you try and add the open class to the elements with the dropdown class on the click event of the toggle, it won't work because the dropdowns are closed automatically when the navbar is toggled. So, you'll have to wait until the collapse is fully shown:
$('.collapse.navbar-collapse').on('shown.bs.collapse', function(){
$('.dropdown').addClass('open');
});
来源:https://stackoverflow.com/questions/26152393/bootstrap-toggle-menu-expand-on-page-load