如何使 Bootstrap 菜单下拉鼠标悬停而不是点击

I'd like to have my Bootstrap menu automatically drop down on hover, rather than having to click the menu title. I'd also like to lose the little arrows next to the menu titles.

转载于:https://stackoverflow.com/questions/8878033/how-to-make-twitter-bootstrap-menu-dropdown-on-hover-rather-than-click

csdnceshi78
程序go Possible duplicate of Bootstrap Dropdown with Hover
接近 2 年之前 回复
csdnceshi70
笑故挽风 Think twice if you really need it? Bootstrap is using for adaptive sites. It means they will be used on devices with touch controls as well. That's why it is designed this way. There is no "hover" on touch screens.
4 年多之前 回复
weixin_41568110
七度&光 I made a pure CSS3 dropdown with a bootstrap navbar check it out on CodePen Pure CSS3 Dropdown
4 年多之前 回复
weixin_41568134
MAO-EYE See my newly published proper plugin which prevents the issues of the below CSS and js solutions, and works fine on iOS and on modern desktop browsers with touch events. Even the aria attributes are working fine with that: github.com/istvan-ujjmeszaros/bootstrap-dropdown-hover
大约 5 年之前 回复
csdnceshi55
~Onlooker There is a solution for that, so mikko's answer is correct but covered now with a plugin for specifically that situation. bootstrap-hover-dropdown
接近 6 年之前 回复

30个回答

I created a pure on hover dropdown menu based on the latest (v2.0.2) Bootstrap framework that has support for multiple submenus and thought I'd post it for future users:

body {
  padding-top: 60px;
  padding-bottom: 40px;
}

.sidebar-nav {
  padding: 9px 0;
}

.dropdown-menu .sub-menu {
  left: 100%;
  position: absolute;
  top: 0;
  visibility: hidden;
  margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
  visibility: visible;
}

.dropdown:hover .dropdown-menu {
  display: block;
}

.nav-tabs .dropdown-menu,
.nav-pills .dropdown-menu,
.navbar .dropdown-menu {
  margin-top: 0;
}

.navbar .sub-menu:before {
  border-bottom: 7px solid transparent;
  border-left: none;
  border-right: 7px solid rgba(0, 0, 0, 0.2);
  border-top: 7px solid transparent;
  left: -7px;
  top: 10px;
}

.navbar .sub-menu:after {
  border-top: 6px solid transparent;
  border-left: none;
  border-right: 6px solid #fff;
  border-bottom: 6px solid transparent;
  left: 10px;
  top: 11px;
  left: -6px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" />

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container-fluid">
      <a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </a>
      <a href="#" class="brand">Project name</a>
      <div class="nav-collapse">
        <ul class="nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
          <li><a href="#">Link</a></li>
          <li class="dropdown">
            <a data-toggle="dropdown" class="dropdown-toggle" href="#">Dropdown <b class="caret"></b></a>
            <ul class="dropdown-menu">
              <li>
                <a href="#">2-level Dropdown <i class="icon-arrow-right"></i></a>
                <ul class="dropdown-menu sub-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li class="divider"></li>
                  <li class="nav-header">Nav header</li>
                  <li><a href="#">Separated link</a></li>
                  <li><a href="#">One more separated link</a></li>
                </ul>
              </li>
              <li><a href="#">Another action</a></li>
              <li><a href="#">Something else here</a></li>
              <li class="divider"></li>
              <li class="nav-header">Nav header</li>
              <li><a href="#">Separated link</a></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
        </ul>
        <form action="" class="navbar-search pull-left">
          <input type="text" placeholder="Search" class="search-query span2">
        </form>
        <ul class="nav pull-right">
          <li><a href="#">Link</a></li>
          <li class="divider-vertical"></li>
          <li class="dropdown">
            <a class="#" href="#">Menu</a>
          </li>
        </ul>
      </div>
      <!-- /.nav-collapse -->
    </div>
  </div>
</div>

<hr>

<ul class="nav nav-pills">
  <li class="active"><a href="#">Regular link</a></li>
  <li class="dropdown">
    <a href="#" data-toggle="dropdown" class="dropdown-toggle">Dropdown <b class="caret"></b></a>
    <ul class="dropdown-menu" id="menu1">
      <li>
        <a href="#">2-level Menu <i class="icon-arrow-right"></i></a>
        <ul class="dropdown-menu sub-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="nav-header">Nav header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
      <li><a href="#">Another action</a></li>
      <li><a href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a href="#">Separated link</a></li>
    </ul>
  </li>
  <li class="dropdown">
    <a href="#">Menu</a>
  </li>
  <li class="dropdown">
    <a href="#">Menu</a>
  </li>
</ul>

Demo

</div>
weixin_41568126
乱世@小熊 Here is the solution for Bootstrap 4.x, with simple 7 lines of CSS code: bootsnipp.com/snippets/Vm7d
大约 2 年之前 回复
weixin_41568127
?yb? this is a long answer, just add .dropdown-menu li:hover .sub-menu { visibility: visible; } .dropdown:hover .dropdown-menu { display: block; }
2 年多之前 回复
csdnceshi67
bug^君 Also you can just use CSS to dropdown: codepen.io/Gothburz/pen/GpJKqP
4 年多之前 回复
csdnceshi54
hurriedly% Here is a code that works with the newest Bootstrap 3 version: jsfiddle.net/sgruenwald/2tt8f8xg
接近 5 年之前 回复
csdnceshi78
程序go Also to make link with children clickable, you have to remove the "data-toggle='dropdown'" on <a> tag.
5 年多之前 回复
weixin_41568184
叼花硬汉 To avoid the auto drop down on smaller devices (such as phones) and aonly allow it as of a min-width of e.g. 768px do @media (min-width: 768px) {.dropdown-menu li:hover .sub-menu {visibility: visible;}} and @media (min-width: 768px) {.dropdown:hover .dropdown-menu {display: block;}}
6 年多之前 回复
csdnceshi75
衫裤跑路 so good! I also removed class="dropdown-toggle" data-toggle="dropdown" so that only hovers, not click would trigger the menu. Note that when you're using responsive styles, the menus still get swept into the little button at top right, which is still triggered by a click. Big Thanks!
7 年多之前 回复
csdnceshi53
Lotus@ it's a design decision in bootstrap to do not open the dropdowns on hover event...
接近 8 年之前 回复

In addition to the answer from "My Head Hurts" (which was great):

ul.nav li.dropdown:hover ul.dropdown-menu{
    display: block;    
}

There are 2 lingering issues:

  1. Clicking on the dropdown link will open the dropdown-menu. And it will stay open unless the user clicks somewhere else, or hovers back over it, creating an awkward UI.
  2. There is a 1px margin between the dropdown link, and dropdown-menu. This causes the dropdown-menu to become hidden if you move slowly between the dropdown and dropdown-menu.

The solution to (1) is removing the "class" and "data-toggle" elements from the nav link

<a href="#">
     Dropdown
     <b class="caret"></b>
</a>

This also gives you the ability to create a link to your parent page - which wasn't possible with the default implementation. You can just replace the "#" with whatever page you want to send the user.

The solution to (2) is removing the margin-top on the .dropdown-menu selector

.navbar .dropdown-menu {
 margin-top: 0px;
}
weixin_41568127
?yb? If you removed the data-toggle="dropdown" attribute, you won't be able to expand the drop down menu using the keyboard. So it will not be 508 compliant. How can you disable the click but keep the keyboard functionality?
接近 5 年之前 回复
csdnceshi53
Lotus@ if we remove "class" and "data-toggle" elements from the nav link as the solution for for problem 1, how can we make it run on mobile devices?? please help
接近 6 年之前 回复
csdnceshi56
lrony* removing "class" and "data-toggle" attributes from nav links make it stop working fine in mobile and tablets :(
大约 6 年之前 回复
csdnceshi51
旧行李 For issue (2), add a transparent border-top instead of the margin-top to keep any intended spacing as well as fixing the ::hover issue.
6 年多之前 回复
csdnceshi79
python小菜 I had to add an !important to effectively solve (2).
6 年多之前 回复
weixin_41568110
七度&光 this
接近 7 年之前 回复
csdnceshi59
ℙℕℤℝ To fix the problem I noted above li.dropdown:hover > ul.dropdown-menu
7 年多之前 回复
csdnceshi58
Didn"t forge Solution (2) for nav-pill buttons: .nav-pills .dropdown-menu { margin-top: 0px; }
接近 8 年之前 回复
csdnceshi64
游.程 To fix the deliberate click, I just removed the data-toggle="dropdown" attribute, which seemed to work.
8 年多之前 回复

To get the menu to automatically drop on hover then this can achieved using basic CSS. You need to work out the selector to the hidden menu option and then set it to display as block when the appropriate li tag is hovered over. Taking the example from the twitter bootstrap page, the selector would be as follows:

ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;    
}

However, if you are using Bootstrap's responsive features, you will not want this functionality on a collapsed navbar (on smaller screens). To avoid this, wrap the code above in a media query:

@media (min-width: 979px) {
  ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;
  }
}

To hide the arrow (caret) this is done in different ways depending on whether you are using Twitter Bootstrap version 2 and lower or version 3:

Bootstrap 3

To remove the caret in version 3 you just need to remove the HTML <b class="caret"></b> from the .dropdown-toggle anchor element:

<a class="dropdown-toggle" data-toggle="dropdown" href="#">
    Dropdown
    <b class="caret"></b>    <-- remove this line
</a>

Bootstrap 2 & lower

To remove the caret in version 2 you need a little more insight into CSS and I suggest looking at how the :after pseudo element works in more detail. To get you started on your way to understanding, to target and remove the arrows in the twitter bootstrap example, you would use the following CSS selector and code:

a.menu:after, .dropdown-toggle:after {
    content: none;
}

It will work in your favour if you look further into how these work and not just use the answers that I have given you.

Thanks to @CocaAkat for pointing out that we were missing the ">" child combinator to prevent sub menus being shown on the parent hover

csdnceshi76
斗士狗 In Bootstrap 4 it has changed, the proper code is div.dropdown instead of ul.dropdown for example: @media (min-width: 992px) { ul.nav li.dropdown:hover > div.dropdown-menu { display: block; } }
2 年多之前 回复
csdnceshi55
~Onlooker This doesn't work well on touch/mobile devices. After clicking the menu the menu indeed opens, but you cannot click the menu again to close it. You have to tap somewhere else in the screen to close it, which, on Chrome-iOS at least, causes a flickering effect.
2 年多之前 回复
csdnceshi62
csdnceshi62 Any update for BS4?
2 年多之前 回复
csdnceshi69
YaoRaoLov I've added this solution to my website, however scrollspy is not working now. Can anyone help me with that ? stackoverflow.com/questions/43853814/…
大约 3 年之前 回复
csdnceshi64
游.程 I think it's important that you bring up that this is not recommended on small screens. On a smartphone, a user would not be able to trigger the hover event because they can't hover with their finger.
大约 4 年之前 回复
csdnceshi77
狐狸.fox - In general, if you come across an issue it is better to open a new question as it will help other visitors and will more likely get your question answered. The code you linked to uses a javascript solution rather than a CSS based solution, which means it is unlikely to share behaviours with this solution. In fact, from quickly looking at the code in the linked example, the problem looks to be in the way the author uses the toggle function.
大约 5 年之前 回复
weixin_41568196
撒拉嘿哟木头 Head Hurts found this which looks like the same problem: bootsnipp.com/snippets/featured/…
大约 5 年之前 回复
weixin_41568196
撒拉嘿哟木头 - i have the same problem, did you find the cause?
大约 5 年之前 回复
weixin_41568131
10.24 I added this css class to make the menu item have a hover over color. .navbar-nav > li.dropdown:hover { background-color: gray ; }
大约 5 年之前 回复
csdnceshi68
local-host The bootstrap 2.x remove caret does not work...
6 年多之前 回复
csdnceshi73
喵-见缝插针 Head Hurts - you're right, I'm unable to reproduce this in a simple example.
6 年多之前 回复
csdnceshi77
狐狸.fox - that sounds like something caused by Javascript. Could you put together a JSFiddle reporducing the issue and I will take a look
6 年多之前 回复
csdnceshi73
喵-见缝插针 One small issue with this solution is that the dropdown menu stays open after clicking on a menu item (until the cursor is moved).
6 年多之前 回复
weixin_41568110
七度&光 to be able to click the link, you must remove the data-toggle="dropdown" attribute.
接近 7 年之前 回复
csdnceshi77
狐狸.fox can you add a JSFiddle demostrating the code "not working" (with an explanation of what is happening and what you are expecting to happen) and I will take a look. I have had a quick look at the CSS classes in Bootstrap 3.0 and they look to be the same - the only change is the way the caret is displayed so I have updated my answer to reflect this!
接近 7 年之前 回复
csdnceshi54
hurriedly% It's not working with ie9
接近 7 年之前 回复
weixin_41568183
零零乙 Opening the dropdown on hover seems awkward a collapsing responsive navbar is in the collapsed state. Enclosing the CSS suggested by MyHeadHurts within a media query that only allows the rule when the width of the window is greater than the width required before the navigation collapses seems to help. /* Make dropdowns activate on hover except when navigation is collapsed by max-width */ @media (min-width: 979px) { ul.nav li.dropdown:hover > ul.dropdown-menu { display: block; } }
大约 7 年之前 回复
csdnceshi61
derek5. Use this jquery plugin for Bootstrap NavBar support hover on specific screen size and clickable on specific screen size.
大约 7 年之前 回复
csdnceshi77
狐狸.fox the first comment by SalmanPK shows the solution to fix this. If this does not resolve the problem then let me know and I will revisit the answer as Twitter Bootstrap is always being updated
7 年多之前 回复
csdnceshi51
旧行李 There is a problem with this approach in that there is a slight gap between the dropdown menu and the actual menu item so if you move slowly it will close the cover
7 年多之前 回复
csdnceshi77
狐狸.fox I don't think it is possible for mods to accept answers on behalf of other people. Luckily the voting system in StackOverflow is a good way to show what the good answers are - which also works well when answers (which are not always the best) are marked as the accepted answer.
7 年多之前 回复
weixin_41568174
from.. Btw it's a pity that this question is not marked as answer. Can a mod do possibly something...?
7 年多之前 回复
csdnceshi52
妄徒之命 For bootstrap 2.1 the first css selector should now be: ul.nav li.dropdown-toggle:hover ul.dropdown-menu { display: block; }
接近 8 年之前 回复
weixin_41568134
MAO-EYE After some further research - turns out this was indeed a Bootstrap bug and it was only fixed five days ago.
接近 8 年之前 回复
csdnceshi77
狐狸.fox Note: Yes it does - this will work in any browser that twitter bootstrap supports. @GeorgeEdison This is basic CSS - what part would not be supported by IE8? If you are having problems, post a question, not misleading comments.
接近 8 年之前 回复
weixin_41568134
MAO-EYE Note: this doesn't work in IE8.
接近 8 年之前 回复
csdnceshi77
狐狸.fox - knock up a fiddle and I will take a look
接近 8 年之前 回复
csdnceshi74
7*4 Simple solution, but the parent link is still not clickable. I'm using latest bootstrap with roots theme.
接近 8 年之前 回复
csdnceshi71
Memor.の Also had to add margin: 0;, otherwise the 1px margin above .dropdown-menu causes buggy behavior.
接近 8 年之前 回复

I've used a bit of jQuery:

// Add hover effect to menus
jQuery('ul.nav li.dropdown').hover(function() {
  jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();
}, function() {
  jQuery(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();
});
weixin_41568127
?yb? this was intended for Bootstrap V1/2 ::: So this solution is not relevant anymore :::
2 年多之前 回复
csdnceshi58
Didn"t forge this doesn't seem to work with jqLite that is included with anguraljs
2 年多之前 回复
csdnceshi79
python小菜 Used this one, nice and small. The css version did not allow submenu to stay displayed, and 200ms was too quick so I changed it to $('ul.nav li.dropdown').hover(function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(); }, function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut().hover(function() { $(this).stop(true, true); }); }); : When the submenu is hover stop fadeOut
4 年多之前 回复
csdnceshi63
elliott.david I used this but also extended it to be useable for dropdowns that are not in a nav. I add class dropdown-hover to the btn-group div and used this jQuery finder $('ul.nav li.dropdown, .dropdown-hover').hover(function() {. Thanks!
大约 6 年之前 回复
csdnceshi53
Lotus@ Used this. I like that it still allows the click functionality as well, for mobiles, but for desktops the hover is perfect.
6 年多之前 回复
csdnceshi62
csdnceshi62 Like this. Am using JQuery anyway with the Bootstrap stuff and still allows for the default 'click' functionality in touchscreen devices.
7 年多之前 回复

Simply customize your CSS style in three lines of code

.dropdown:hover .dropdown-menu {
   display: block;
}

[Update] The plugin is on GitHub and I am working on some improvements (like use only with data-attributes (no JS necessary). I've leaving the code in below, but it's not the same as what's on GitHub.

I liked the purely CSS version, but it's nice to have a delay before it closes, as it's usually a better user experience (i.e. not punished for a mouse slip that goes 1 px outside the dropdown, etc), and as mentioned in the comments, there's that 1px of margin you have to deal with or sometimes the nav closes unexpectedly when you're moving to the dropdown from the original button, etc.

I created a quick little plugin that I've used on a couple sites and it's worked nicely. Each nav item is independently handled, so they have their own delay timers, etc.

JS

// outside the scope of the jQuery plugin to
// keep track of all dropdowns
var $allDropdowns = $();

// if instantlyCloseOthers is true, then it will instantly
// shut other nav items when a new one is hovered over
$.fn.dropdownHover = function(options) {

    // the element we really care about
    // is the dropdown-toggle's parent
    $allDropdowns = $allDropdowns.add(this.parent());

    return this.each(function() {
        var $this = $(this).parent(),
            defaults = {
                delay: 500,
                instantlyCloseOthers: true
            },
            data = {
                delay: $(this).data('delay'),
                instantlyCloseOthers: $(this).data('close-others')
            },
            options = $.extend(true, {}, defaults, options, data),
            timeout;

        $this.hover(function() {
            if(options.instantlyCloseOthers === true)
                $allDropdowns.removeClass('open');

            window.clearTimeout(timeout);
            $(this).addClass('open');
        }, function() {
            timeout = window.setTimeout(function() {
                $this.removeClass('open');
            }, options.delay);
        });
    });
};  

The delay parameter is pretty self explanatory, and the instantlyCloseOthers will instantly close all other dropdowns that are open when you hover over a new one.

Not pure CSS, but hopefully will help someone else at this late hour (i.e. this is an old thread).

If you want, you can see the different processes I went through (in a discussion on the #concrete5 IRC) to get it to work via the different steps in this gist: https://gist.github.com/3876924

The plugin pattern approach is much cleaner to support individual timers, etc.

See the blog post for more.

This is built into Bootstrap 3. Just add this to your CSS:

.dropdown:hover .dropdown-menu {
display: block;
}
$('.dropdown').hover(function(e){$(this).addClass('open')})
csdnceshi63
elliott.david Please provide some details to your answer.
3 年多之前 回复

The jQuery solution is good, but it will need to either deal with on click events (for mobile or tablet) as hover won't work properly... Could maybe do some window re-size detection?

Andres Ilich's answer seems to work well, but it should be wrapped in a media query:

@media (min-width: 980px) {

    .dropdown-menu .sub-menu {
        left: 100%;
        position: absolute;
        top: 0;
        visibility: hidden;
        margin-top: -1px;
    }

    .dropdown-menu li:hover .sub-menu {
        visibility: visible;
    }

    .dropdown:hover .dropdown-menu {
        display: block;
    }

    .nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu {
        margin-top: 0;
    }

    .navbar .sub-menu:before {
        border-bottom: 7px solid transparent;
        border-left: none;
        border-right: 7px solid rgba(0, 0, 0, 0.2);
        border-top: 7px solid transparent;
        left: -7px;
        top: 10px;
    }
    .navbar .sub-menu:after {
        border-top: 6px solid transparent;
        border-left: none;
        border-right: 6px solid #fff;
        border-bottom: 6px solid transparent;
        left: 10px;
        top: 11px;
        left: -6px;
    }
}

Overwrite bootstrap.js with this script.

jQuery(document).ready(function ($) {
$('.navbar .dropdown').hover(function() {
    $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
    var na = $(this)
    na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function(){ na.removeClass('extra-nav-class') })
});

$('.dropdown-submenu').hover(function() {
    $(this).addClass('extra-nav-class').find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
    var na = $(this)
    na.find('.dropdown-menu').first().stop(true, true).delay(100).slideUp('fast', function(){ na.removeClass('extra-nav-class') })
});

}); 
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问