jQuery Bootstrap 3 下拉菜单:悬停和点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24685000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:38:51  来源:igfitidea点击:

Bootstrap 3 Dropdowns: on Hover and on Click

jqueryhtmlcssresponsive-designtwitter-bootstrap-3

提问by user3694391

Nearly all the links on my navbar are dropdowns. I would like them to appear on hover for large screens, but on click for smaller screens. Is that possible? In my search for the answer, I came across this: Bootstrap Menu: Dropdown on Hover for Desktop Only. This doesn't work for me because I don't want the entire dropdown to be invisible on mobile; I'd only like it to be visible on click instead of on hover.

我导航栏上的几乎所有链接都是下拉菜单。我希望它们出现在大屏幕悬停时,但在小屏幕上单击。那可能吗?在我寻找答案时,我遇到了这个:Bootstrap Menu: Dropdown on Hover for Desktop Only。这对我不起作用,因为我不希望整个下拉菜单在移动设备上不可见;我只希望它在点击时可见,而不是在悬停时可见。

回答by jme11

EDITEDThe answer from @ouwen-huang is fine, but since jQuery is a dependency for bootstrap.js, you might as well do it the jQuery way by just adding all of the events that you want to attach to in quotes space-separated:

已编辑@ouwen-huang 的答案很好,但由于 jQuery 是 bootstrap.js 的依赖项,您不妨以 jQuery 方式执行此操作,只需将要附加到的所有事件添加到以空格分隔的引号中:

$('.dropdown').on('mouseenter mouseleave click tap', function() {
  $(this).toggleClass("open");
});

The selectors are based on the standard Bootstrap markup, taken directly from the docs like so:

选择器基于标准 Bootstrap 标记,直接取自文档,如下所示:

<li class="dropdown">
    <a id="drop1" href="#" role="button" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a>
    <ul class="dropdown-menu" role="menu" aria-labelledby="drop1">
        <li role="presentation"><a role="menuitem" tabindex="-1" href="http://twitter.com/fat">Action</a></li>
        <li role="presentation"><a role="menuitem" tabindex="-1" href="http://twitter.com/fat">Another action</a></li>
        <li role="presentation"><a role="menuitem" tabindex="-1" href="http://twitter.com/fat">Something else here</a></li>
        <li role="presentation" class="divider"></li>
        <li role="presentation"><a role="menuitem" tabindex="-1" href="http://twitter.com/fat">Separated link</a></li>
    </ul>
</li>

The point here is that if you are on a mouse-enabled device like a desktop that doesn't have touch capability, then the mouseenter/mouseleave events are fired and the menu is activated without a click. If the user is not on a device that fires a mouseenter/mouseleave event then the click or tap events are fired when the person taps the link and the click or tap handler handles the dropdown toggle.

这里的重点是,如果您使用的是支持鼠标的设备,例如没有触摸功能的桌面,则 mouseenter/mouseleave 事件将被触发,并且无需单击即可激活菜单。如果用户不在触发 mouseenter/mouseleave 事件的设备上,则当用户点击链接并且点击或点击处理程序处理下拉切换时,将触发 click 或 tap 事件。

EDITED for accuracy.

为准确性而编辑。

回答by James Herrington

The other 2 solutions work but don't keep the bootstrap styling. A simpler solution is to just add the 'open' class.

其他 2 个解决方案有效,但不保留引导程序样式。一个更简单的解决方案是只添加“开放”类。

$('.dropdown').on('mouseenter mouseleave click tap', function() {
  $(this).toggleClass("open");
});

回答by Ouwen Huang

You can use javascript events for this.

您可以为此使用 javascript 事件。

Using the mobile check library you can say

使用移动检查库,您可以说

var domObject = document.querySelector('.myClassOrIDWhateverFloatsYourBoat');
if(mobile checked is true){
    domObject.addEventListener('hover', function(){
        $('.dropdown-toggle').dropdown();  // http://getbootstrap.com/javascript/
    })
}else{
   domObject.addEventListener('click', function(){
        $('.dropdown-toggle').dropdown();  // http://getbootstrap.com/javascript/
    })
}

回答by Paul

After trying many plugins and solutions posted across stackoverflow I came up with rather simple code that:

在尝试了许多跨 stackoverflow 发布的插件和解决方案后,我想出了相当简单的代码:

  • shows dropdown on hover by native Bootstrap class (so it cooperates well with button click)
  • makes button link work when href is set
  • keeps original behaviour on mobile devices
  • 通过本机 Bootstrap 类在悬停时显示下拉菜单(因此它与按钮单击配合良好)
  • 设置 href 时使按钮链接工作
  • 在移动设备上保持原始行为

Simple version

简单版

$('ul.nav li.dropdown').hover(function() {
    if (!$('.navbar-toggle').is(':visible')) {
        $(this).toggleClass('open', true);
    }
}, function() {
    if (!$('.navbar-toggle').is(':visible')) {
        $(this).toggleClass('open', false);
    }
});
$('ul.nav li.dropdown a').click(function(){
    if (!$('.navbar-toggle').is(':visible') && $(this).attr('href') != '#') {
        $(this).toggleClass('open', false);
        window.location = $(this).attr('href')
    }
});

$('.navbar-toggle').is(':visible')checks if we are currently in mobile view, $(this).toggleClass('open', true)adds or removes opencss class used by bootstrap, and window.location = $(this).attr('href')sends user to location set in the link href.

$('.navbar-toggle').is(':visible')检查我们当前是否在移动视图中, $(this).toggleClass('open', true)添加或删除open引导程序使用的 css 类,window.location = $(this).attr('href')并将用户发送到链接 href 中设置的位置。



To add jQuery transitions we have to modify the script a little bit.

要添加 jQuery 转换,我们必须稍微修改脚本。

Modified version

修改版

visible = false;

function toggleDropdown(dropdown, delay, fade, state) {
    if (state === undefined) visible = !visible
    else visible = state

    dropdown.children('.dropdown-menu').stop(true, true).delay(delay)[visible ? 'fadeIn' : 'fadeOut'](fade, function() {
        dropdown.toggleClass('open', visible);
        dropdown.children('.dropdown-toggle').attr('aria-expanded', visible);
        $(this).css('display', '');
    });
}

$('ul.nav li.dropdown').hover(function() {
    if ($('.navbar-toggle').is(':visible')) return;
    toggleDropdown($(this), 50, 100, true)
}, function() {
    if ($('.navbar-toggle').is(':visible')) return;
    toggleDropdown($(this), 400, 200, false)
});

$('ul.nav li.dropdown a').click(function(){
    if ($('.navbar-toggle').is(':visible')) return;
    if ($(this).attr('href') != '#') {
        toggleDropdown($(this).parent(), 50, 100, false)
        window.location = $(this).attr('href')
    }
    else {
        toggleDropdown($(this).parent(), 50, 100)
    }
});

visiblevariable makes everything work nicely when re-hovering while animation is running.

visible变量使动画运行时重新悬停时一切正常。

回答by Lucas L Jordan

// toggle dropdown on mouse hover, click and tap events
$('.dropdown').on('mouseenter mouseleave click tap touchstart', function(event) {
    if (!$('.navbar-toggle').is(':visible')) {
        $(this).dropdown('toggle');
    }
});

Here is a slightly modified version of @jme11 's Answer based on the Bootstrap 3 documentation for Javascript Dropdowns.The advantage of using this method is that it enables the drop down to function exactly as intended without having to modify any classes and is therefore cleaner IMO.

这是基于Javascript DropdownsBootstrap 3 文档的 @jme11 答案的略微修改版本使用此方法的优点是它使下拉菜单能够完全按预期运行,而无需修改任何类,因此 IMO 更干净。

Codepen Example

代码笔示例

回答by paddyfields

A nice way to achieve this is to have hover enabled only when the menu is not collapsed.

实现此目的的一个好方法是仅在菜单未折叠时启用悬停。

$('.dropdown').on('mouseenter mouseleave click tap', function(event) {
  if (!$('.navbar-toggle').is(':visible')) {
    $(this).toggleClass("open");
  }
});

回答by Stillmatic1985

For Bootstrap 4 following code works.

对于 Bootstrap 4,以下代码有效。

$('.dropdown').on('mouseenter mouseleave click tap', function() {
    $(this).toggleClass("show");
});

回答by Maggie Murry

This is simple and works well, but on mobile, if you open a submenu and click on the menu item to close, it doesn't close

这很简单而且效果很好,但是在移动设备上,如果您打开子菜单并单击要关闭的菜单项,它不会关闭

$('.dropdown').on('mouseenter mouseleave click tap', function() {
  $(this).toggleClass("open");
});