Javascript 向 bootstrap 下拉菜单添加滑动效果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12115833/
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-23 07:08:33  来源:igfitidea点击:

Adding a slide effect to bootstrap dropdown

javascriptdrop-down-menutwitter-bootstrap

提问by Ben Beri

I'm using bootstrap, and I'd like to add animation to a dropdown. I want to add an animation to it, slide down and back up when leaving it. How could I do this?

我正在使用bootstrap,我想将动画添加到下拉列表中。我想给它添加一个动画,离开时向下滑动并返回。我怎么能这样做?

Things I tried:

我尝试过的事情:

Changing the Js drop down file like this:

像这样更改 Js 下拉文件:

How can I make Bootstrap's navigation dropdown slide smoothly up and down?

如何让 Bootstrap 的导航下拉菜单平滑地上下滑动?

回答by cogell

If you update to Bootstrap 3 (BS3), they've exposed a lot of Javascript events that are nice to tie your desired functionality into. In BS3, this code will give all of your dropdown menus the animation effect you are looking for:

如果您更新到 Bootstrap 3 (BS3),它们会公开许多 Javascript 事件,这些事件可以很好地将您想要的功能绑定到其中。在 BS3 中,此代码将为您的所有下拉菜单提供您正在寻找的动画效果:

  // Add slideDown animation to Bootstrap dropdown when expanding.
  $('.dropdown').on('show.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
  });

  // Add slideUp animation to Bootstrap dropdown when collapsing.
  $('.dropdown').on('hide.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
  });

You can read about BS3 events hereand specifically about the dropdown events here.

你可以阅读有关BS3的事件在这里,特别对下拉事件在这里

回答by MadisonTrash

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

此外,通过将以下一小段代码添加到您的样式中,可以避免使用 JavaScript 来实现下拉效果,并使用 CSS3 过渡:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

这种方式的唯一问题是您应该手动指定 max-height。如果你设置一个非常大的值,你的动画会很快。

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

如果您知道下拉列表的大致高度,它就像一个魅力,否则您仍然可以使用 javascript 来设置精确的 max-height 值。

Here is small example: DEMO

这是小例子:DEMO



! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.

!此解决方案中存在带有填充的小错误,请查看 Jacob Stamm 对解决方案的评论。

回答by Yohn

I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click

我正在做类似的事情,但在悬停而不是点击..这是我正在使用的代码,您可以稍微调整一下以使其在点击时工作

$('.navbar .dropdown').hover(function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});

回答by IndieRok

I don't know if I can bump this thread, but I figured out a quick fix for the visual bug that happens when the open class is removed too fast. Basically, all there is to it is to add an OnComplete function inside the slideUp event and reset all active classes and attributes. Goes something like this:

我不知道我是否可以撞到这个线程,但我想出了一个快速修复开放类删除太快时发生的视觉错误的方法。基本上,所有要做的就是在 slideUp 事件中添加一个 OnComplete 函数并重置所有活动的类和属性。是这样的:

Here is the result: Bootply example

结果如下:Bootply 示例

Javascript/Jquery:

Javascript/Jquery:

$(function(){
    // ADD SLIDEDOWN ANIMATION TO DROPDOWN //
    $('.dropdown').on('show.bs.dropdown', function(e){
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
    });

    // ADD SLIDEUP ANIMATION TO DROPDOWN //
    $('.dropdown').on('hide.bs.dropdown', function(e){
        e.preventDefault();
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(400, function(){
            //On Complete, we reset all active dropdown classes and attributes
            //This fixes the visual bug associated with the open class being removed too fast
            $('.dropdown').removeClass('show');
            $('.dropdown-menu').removeClass('show');
            $('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
        });
    });
});

回答by Vedmant

here is my solution for slide & fade effect:

这是我的幻灯片和淡入淡出效果的解决方案:

   // Add slideup & fadein animation to dropdown
   $('.dropdown').on('show.bs.dropdown', function(e){
      var $dropdown = $(this).find('.dropdown-menu');
      var orig_margin_top = parseInt($dropdown.css('margin-top'));
      $dropdown.css({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}).animate({'margin-top': orig_margin_top + 'px', opacity: 1}, 300, function(){
         $(this).css({'margin-top':''});
      });
   });
   // Add slidedown & fadeout animation to dropdown
   $('.dropdown').on('hide.bs.dropdown', function(e){
      var $dropdown = $(this).find('.dropdown-menu');
      var orig_margin_top = parseInt($dropdown.css('margin-top'));
      $dropdown.css({'margin-top': orig_margin_top + 'px', opacity: 1, display: 'block'}).animate({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}, 300, function(){
         $(this).css({'margin-top':'', display:''});
      });
   });

回答by Abhimanyu Rana

On click it can be done using below code

单击它可以使用以下代码完成

$('.dropdown-toggle').click(function() {
  $(this).next('.dropdown-menu').slideToggle(500);
});

回答by Zim

Update 2018 Bootstrap 4

更新 2018 Bootstrap 4

In Boostrap 4, the .openclass has been replaced with .show. I wanted to implement this using only CSS transistions without the need for extra JS or jQuery...

在 Boostrap 4 中,.open该类已被替换为.show. 我想仅使用 CSS 转换来实现这一点,而无需额外的 JS 或 jQuery ...

.show > .dropdown-menu {
  max-height: 900px;
  visibility: visible;
}

.dropdown-menu {
  display: block;
  max-height: 0;
  visibility: hidden;
  transition: all 0.5s ease-in-out;
  overflow: hidden;
}

Demo: https://www.codeply.com/go/3i8LzYVfMF

演示:https: //www.codeply.com/go/3i8LzYVfMF

Note: max-heightcan be set to any large value that's enough to accommodate the dropdown content.

注意:max-height可以设置为足以容纳下拉内容的任何大值。

回答by Augusto Triste

I am using the code above but I have changed the delay effect by slideToggle.

我正在使用上面的代码,但我已经通过 slideToggle 更改了延迟效果。

It slides the dropdown on hover with animation.

它通过动画在悬停时滑动下拉列表。

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400);
    }, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400)
    });

回答by Tom James

Expanded answer, was my first answer so excuse if there wasn't enough detail before.

扩展答案,是我的第一个答案,所以如果之前没有足够的细节,请原谅。

For Bootstrap 3.x I personally prefer CSS animations and I've been using animate.css & along with the Bootstrap Dropdown Javascript Hooks. Although it might not have the exactly effect you're after it's a pretty flexible approach.

对于 Bootstrap 3.x,我个人更喜欢 CSS 动画,我一直在使用 animate.css 和 Bootstrap Dropdown Javascript Hooks。尽管它可能没有您所追求的确切效果,但它是一种非常灵活的方法。

Step 1:Add animate.css to your page with the head tags:

第 1 步:使用 head 标签将 animate.css 添加到您的页面:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css">

Step 2:Use the standard Bootstrap HTML on the trigger:

第 2 步:在触发器上使用标准的 Bootstrap HTML:

<div class="dropdown">
  <button type="button" data-toggle="dropdown">Dropdown trigger</button>

  <ul class="dropdown-menu">
    ...
  </ul>
</div>

Step 3:Then add 2 custom data attributes to the dropdrop-menu element; data-dropdown-in for the in animation and data-dropdown-out for the out animation. These can be any animate.css effects like fadeIn or fadeOut

第三步:然后在dropdrop-menu元素中添加2个自定义数据属性;输入动画的 data-dropdown-in 和输出动画的 data-dropdown-out。这些可以是任何 animate.css 效果,如fadeIn 或fadeOut

<ul class="dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
......
</ul>

Step 4:Next add the following Javascript to read the data-dropdown-in/out data attributes and react to the Bootstrap Javascript API hooks/events (http://getbootstrap.com/javascript/#dropdowns-events):

第 4 步:接下来添加以下 Javascript 以读取 data-dropdown-in/out 数据属性并对 Bootstrap Javascript API 钩子/事件(http://getbootstrap.com/javascript/#dropdowns-events)做出反应:

var dropdownSelectors = $('.dropdown, .dropup');

// Custom function to read dropdown data
// =========================
function dropdownEffectData(target) {
  // @todo - page level global?
  var effectInDefault = null,
      effectOutDefault = null;
  var dropdown = $(target),
      dropdownMenu = $('.dropdown-menu', target);
  var parentUl = dropdown.parents('ul.nav'); 

  // If parent is ul.nav allow global effect settings
  if (parentUl.size() > 0) {
    effectInDefault = parentUl.data('dropdown-in') || null;
    effectOutDefault = parentUl.data('dropdown-out') || null;
  }

  return {
    target:       target,
    dropdown:     dropdown,
    dropdownMenu: dropdownMenu,
    effectIn:     dropdownMenu.data('dropdown-in') || effectInDefault,
    effectOut:    dropdownMenu.data('dropdown-out') || effectOutDefault,  
  };
}

// Custom function to start effect (in or out)
// =========================
function dropdownEffectStart(data, effectToStart) {
  if (effectToStart) {
    data.dropdown.addClass('dropdown-animating');
    data.dropdownMenu.addClass('animated');
    data.dropdownMenu.addClass(effectToStart);    
  }
}

// Custom function to read when animation is over
// =========================
function dropdownEffectEnd(data, callbackFunc) {
  var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
  data.dropdown.one(animationEnd, function() {
    data.dropdown.removeClass('dropdown-animating');
    data.dropdownMenu.removeClass('animated');
    data.dropdownMenu.removeClass(data.effectIn);
    data.dropdownMenu.removeClass(data.effectOut);

    // Custom callback option, used to remove open class in out effect
    if(typeof callbackFunc == 'function'){
      callbackFunc();
    }
  });
}

// Bootstrap API hooks
// =========================
dropdownSelectors.on({
  "show.bs.dropdown": function () {
    // On show, start in effect
    var dropdown = dropdownEffectData(this);
    dropdownEffectStart(dropdown, dropdown.effectIn);
  },
  "shown.bs.dropdown": function () {
    // On shown, remove in effect once complete
    var dropdown = dropdownEffectData(this);
    if (dropdown.effectIn && dropdown.effectOut) {
      dropdownEffectEnd(dropdown, function() {}); 
    }
  },  
  "hide.bs.dropdown":  function(e) {
    // On hide, start out effect
    var dropdown = dropdownEffectData(this);
    if (dropdown.effectOut) {
      e.preventDefault();   
      dropdownEffectStart(dropdown, dropdown.effectOut);   
      dropdownEffectEnd(dropdown, function() {
        dropdown.dropdown.removeClass('open');
      }); 
    }    
  }, 
});

Step 5 (optional):If you want to speed up or alter the animation you can do so with CSS like the following:

第 5 步(可选):如果你想加速或改变动画,你可以使用 CSS 来实现,如下所示:

.dropdown-menu.animated {
  /* Speed up animations */
  -webkit-animation-duration: 0.55s;
  animation-duration: 0.55s;
  -webkit-animation-timing-function: ease;
  animation-timing-function: ease;
}

Wrote an article with more detail and a download if anyones interested: article: http://bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss

如果有人感兴趣,可以写一篇更详细的文章和下载:文章:http: //bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss

Hope that's helpful & this second write up has the level of detail that's needed Tom

希望这会有所帮助,这第二篇文章具有所需的详细程度,汤姆

回答by ChapDaddy65

$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});

This code works if you want to reveal dropdowns on hover.

如果您想在悬停时显示下拉菜单,则此代码有效。

I just changed the .slideToggleto .slideDown& .slideUp, and removed the (400)timing

我只是将其更改.slideToggle.slideDown& .slideUp,并删除了(400)时间