Agregar un efecto de diapositiva al menú desplegable bootstrap


Estoy usando bootstrap, y me gustaría agregar animación a un menú desplegable.

Quiero añadir una animación a ella, deslizarse hacia abajo y hacia arriba al salir de ella.

¿Cómo podría hacer esto?

Cosas que probé:

Cambiando el archivo desplegable Js de esta manera:

¿Cómo puedo hacer que el menú desplegable de navegación de Bootstrap se deslice suavemente hacia arriba y hacia abajo?

Cualquier ayuda sería buena! ¡Gracias!.

Author: Community, 2012-08-24

12 answers

Si actualizas a Bootstrap 3 (BS3), han expuesto muchos eventos de Javascript que son agradables para vincular la funcionalidad deseada. En BS3, este código le dará a todos sus menús desplegables el efecto de animación que está buscando:

  // 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();
  });

Puedes leer sobre los eventos BS3 aquí y específicamente sobre los eventos desplegables aquí.

 127
Author: cogell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-15 12:37:36

También es posible evitar el uso de JavaScript para el efecto desplegable, y usar la transición CSS3, agregando este pequeño fragmento de código a su estilo:

.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 {
    max-height: 300px;
    opacity: 1;
}

El único problema de esta manera es que debe especificar manualmente max-height. Si establece un valor muy grande, su animación será muy rápida.

Funciona como un encanto si conoce la altura aproximada de sus desplegables, de lo contrario, aún puede usar javascript para establecer un valor de altura máxima preciso.

Aquí es pequeño ejemplo: DEMO


! Hay un pequeño error con relleno en esta solución, revise el comentario de Jacob Stamm con solución.

 55
Author: MadisonTrash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-03 16:00:59

Estoy haciendo algo como eso, pero en hover en lugar de hacer clic.. Este es el código que estoy usando, es posible que pueda retocarlo un poco para que funcione en 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()
});
 20
Author: Yohn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 19:42:43

No se si puedo bump este hilo, pero me di cuenta de una solución rápida para el error visual que ocurre cuando la clase abierta se elimina demasiado rápido. Básicamente, todo lo que hay que hacer es agregar una función onComplete dentro del evento slideUp y restablecer todas las clases y atributos activos. Dice algo como esto:

Aquí está el resultado: Ejemplo Bootply

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('open');
            $('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
        });
    });
});
 15
Author: IndieRok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-10 14:54:26

Aquí está mi solución para el efecto slide & fade:

   // 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:''});
      });
   });
 10
Author: Vedmant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-22 19:24:51

Al hacer clic se puede hacer usando el siguiente código

$('.dropdown-toggle').click(function() {
  $(this).next('.dropdown-menu').slideToggle(500);
});
 8
Author: Abhimanyu Rana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-30 17:18:37

Estoy usando el código anterior, pero he cambiado el efecto de retardo por slideToggle.

Se desliza el menú desplegable en hover con animación.

$('.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)
    });
 7
Author: Augusto Triste,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-10 23:16:41

Respuesta expandida, fue mi primera respuesta así que disculpa si no había suficiente detalle antes.

Para Bootstrap 3.x Personalmente prefiero animaciones CSS y he estado usando animate.css y junto con los ganchos desplegables de Javascript de Bootstrap. Aunque puede que no tenga el efecto exacto que buscas, es un enfoque bastante flexible.

Paso 1: Añadir animate.css a su página con las etiquetas principales:

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

Paso 2: Utilice el HTML de arranque estándar en el trigger:

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

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

Paso 3: Luego agregue 2 atributos de datos personalizados al elemento dropdrop-menu; data-dropdown-in para la animación in y data-dropdown-out para la animación out. Estos pueden ser cualquier animado.efectos css como fadeIn o fadeOut

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

Paso 4: A continuación, agregue el siguiente Javascript para leer los atributos de datos-desplegable-entrada / salida y reaccionar a los hooks/eventos de la API de Javascript de Bootstrap ( 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');
      }); 
    }    
  }, 
});

Paso 5 (opcional): Si quieres acelerar o alterar la animación puedes hacerlo con CSS como el siguiente:

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

Escribió un artículo con más detalle y una descarga si anyones interesado: artículo: http://bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss

Espero que eso sea útil y este segundo escrito tiene el nivel de detalle que se necesita Tom

 3
Author: Tom James,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-26 18:39:23
$('.navbar .dropdown').hover(function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});

Este código funciona si desea revelar menús desplegables al pasar el ratón por encima.

Acabo de cambiar el .slideToggle a .slideDown & .slideUp, y quita el (400) sincronización

 2
Author: ChapDaddy65,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-23 20:05:27

BOOTSTRAP 3 REFERENCIA

Añadido porque sigo siendo atrapado por la solución en este hilo y me rellena cada vez.

Básicamente el menú desplegable BS elimina inmediatamente la clase .open del padre, por lo que deslizarse hacia arriba no funciona.

Use el mismo bit que otras soluciones para slideDown ();

// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
  e.preventDefault();
  $(this).find('.dropdown-menu').first().stop(true, true).slideUp(300, function(){
    $(this).parent().removeClass('open');
  });
});
 1
Author: Slipoch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-08 04:20:00

Aquí hay una buena solución simple usando jQuery que funciona muy bien:

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

$('.dropdown-toggle').focusout(function () {
    $(this).next('.dropdown-menu').slideUp(300);
})

El conmutador de animación de diapositivas se produce al hacer clic y siempre se desliza de nuevo al perder el enfoque.

Altere el valor 300 a cualquier cosa que desee, cuanto menor sea el número, más rápida será la animación.

Editar:

Esta solución solo funcionará para vistas de escritorio. Necesitará algunas modificaciones adicionales con el fin de mostrar muy bien para el móvil.

 0
Author: Barry Michael Doyle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-27 19:29:15

Actualización 2018 Bootstrap 4

En Boostrap 4, la clase .open ha sido reemplazada por .show. Quería implementar esto usando solo transiciones CSS sin la necesidad de JS o jQuery adicionales...

.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

Nota: max-height se puede establecer en cualquier valor grande que sea suficiente para acomodar el contenido desplegable.

 0
Author: Zim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-25 16:00:07