Как я могу перейти высоту: 0;по высоте: авто;используя CSS? - PullRequest
1874 голосов
/ 18 августа 2010

Я пытаюсь заставить <ul> скользить вниз, используя CSS-переходы.

<ul> начинается с height: 0;.При наведении высота установлена ​​на height:auto;.Тем не менее, это приводит к тому, что он просто появляется, не переход,

Если я сделаю это с height: 40px; до height: auto;, то он снизится до height: 0;, а затемвнезапно прыгнуть на правильную высоту.

Как еще я могу сделать это без использования JavaScript?

#child0 {
  height: 0;
  overflow: hidden;
  background-color: #dedede;
  -moz-transition: height 1s ease;
  -webkit-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
}
#parent0:hover #child0 {
  height: auto;
}
#child40 {
  height: 40px;
  overflow: hidden;
  background-color: #dedede;
  -moz-transition: height 1s ease;
  -webkit-transition: height 1s ease;
  -o-transition: height 1s ease;
  transition: height 1s ease;
}
#parent40:hover #child40 {
  height: auto;
}
h1 {
  font-weight: bold;
}
The only difference between the two snippets of CSS is one has height: 0, the other height: 40.
<hr>
<div id="parent0">
  <h1>Hover me (height: 0)</h1>
  <div id="child0">Some content
    <br>Some content
    <br>Some content
    <br>Some content
    <br>Some content
    <br>Some content
    <br>
  </div>
</div>
<hr>
<div id="parent40">
  <h1>Hover me (height: 40)</h1>
  <div id="child40">Some content
    <br>Some content
    <br>Some content
    <br>Some content
    <br>Some content
    <br>Some content
    <br>
  </div>
</div>

Ответы [ 45 ]

0 голосов
/ 03 марта 2014

Я столкнулся с этой проблемой и нашел свой обходной путь.

Сначала я попытался использовать max-height. Но есть две проблемы:

  1. Я не совсем уверен, что такое max-height, так как я расширяю текстовый блок неизвестной длины.
  2. Если я установлю max-height слишком большим, при сжатии будет большая задержка.

Тогда мой обходной путь:

function toggleBlock(e) {
    var target = goog.dom.getNextElementSibling(e.target);
    if (target.style.height && target.style.height != "0px") { //collapsing
        goog.style.setHeight(target, target.clientHeight);
        setTimeout(function(){
            target.style.height = "0px";
        }, 100);
    } else { //expanding
        target.style.height = "auto";
        //get the actual height
        var height = target.clientHeight;
        target.style.height = "0px";
        setTimeout(function(){
            goog.style.setHeight(target, height);
        }, 100);
        setTimeout(function(){
            //Set this because I have expanding blocks inside expanding blocks
            target.style.height="auto";
        }, 600); //time is set 100 + transition-duration
    }
}

Ссс:

div.block {
    height: 0px;
    overflow: hidden;
    @include transition-property(height);
    @include transition-duration(0.5s);
}
0 голосов
/ 09 февраля 2019

Это то, что работает для меня:

  .hide{
    max-height: 0px;
    overflow: hidden;
    transition:max-height .5s ease-in-out;
  }

  .show{
    max-height: 150px; // adjust as needed
    transition: max-height .5s ease-in-out;
  }

вам нужно поместить их во все ваши дочерние компоненты и переключить их с состоянием jQuery или React, вот мой случай (с next.js и styled-components)): https://codesandbox.io/s/ol3kl56q9q

0 голосов
/ 01 июля 2016

Ознакомьтесь с моим постом по несколько схожему вопросу.

По сути, начните с height: 0px; и дайте ему перейти к точной высоте, вычисленной с помощью JavaScript.

function setInfoHeight() {
  $(window).on('load resize', function() {
    $('.info').each(function () {
      var current = $(this);
      var closed = $(this).height() == 0;
      current.show().height('auto').attr('h', current.height() );
      current.height(closed ? '0' : current.height());
    });
  });

Всякий раз, когда страница загружается / изменяется, элемент с классом info обновляет свой атрибут h.Затем кнопка вызывает style="height: __", чтобы установить для него ранее установленное значение h.

function moreInformation() {
  $('.icon-container').click(function() {
    var info = $(this).closest('.dish-header').next('.info'); // Just the one info
    var icon = $(this).children('.info-btn'); // Select the logo

    // Stop any ongoing animation loops. Without this, you could click button 10
    // times real fast, and watch an animation of the info showing and closing
    // for a few seconds after
    icon.stop();
    info.stop();

    // Flip icon and hide/show info
    icon.toggleClass('flip');

    // Metnod 1, animation handled by JS
    // info.slideToggle('slow');

    // Method 2, animation handled by CSS, use with setInfoheight function
    info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');

  });
};

Вот стиль для класса info.

.info {
  padding: 0 1em;
  line-height: 1.5em;
  display: inline-block;
  overflow: hidden;
  height: 0px;
  transition: height 0.6s, padding 0.6s;
  &.active {
    border-bottom: $thin-line;
    padding: 1em;
  }
}

Стиль можетНе поддерживается кросс-браузер.Вот живой пример для этого кода:

CodePen

0 голосов
/ 14 июня 2019

Для чисто CSS-решения, которое анимирует max-height, у которого нет большой задержки, я бы посоветовал установить разумное max-height при наведении, где-то около 500 пикселей или примерно или чуть больше, чем высота большинства элементы, которые вы хотите анимировать, имеют большую прокрутку содержимого, установив overflow-y в auto после завершения анимации с задержкой 0,5 с.

Затем установите время перехода около 0,3 с (или немного медленнее, если расширение приведет к перемещению другого контента на вашей странице) с экспоненциальной кривой кубического безье при открытии и кубическим замедлением -безопаснее и немного быстрее при закрытии, например, 0,15 с, например, когда люди отклоняют что-то со страницы, они, как правило, не хотят ждать, пока они не исчезнут.

Эти быстрые анимации будут по-прежнему видны пользователю и сводят к минимуму эффект любой задержки максимальной высоты, вызывающей вялость вашей страницы.

Код будет выглядеть примерно так:

#child0 {
  max-height: 0;
  overflow-y: hidden;
  background-color: #dedede;
  -webkit-transition: max-height 0.15s cubic-bezier(0.7, 0, 1, 0.5), overflow-y 0s linear 0s;
  -moz-transition: max-height 0.15s cubic-bezier(0.7, 0, 1, 0.5), overflow-y 0s linear 0s;
  -o-transition: max-height 0.15s cubic-bezier(0.7, 0, 1, 0.5), overflow-y 0s linear 0s;
  transition: max-height 0.15s cubic-bezier(0.7, 0, 1, 0.5), overflow-y 0s linear 0s;
}
#parent0:hover #child0 {
  max-height: 500px;
  overflow-y: auto;
  -webkit-transition: max-height 0.3s cubic-bezier(0.1, 0.9, 0.2, 1), overflow-y 0s linear 0.3s;
  -moz-transition: max-height 0.3s cubic-bezier(0.1, 0.9, 0.2, 1), overflow-y 0s linear 0.3s;
  -o-transition: max-height 0.3s cubic-bezier(0.1, 0.9, 0.2, 1), overflow-y 0s linear 0.3s;
  transition: max-height 0.3s cubic-bezier(0.1, 0.9, 0.2, 1), overflow-y 0s linear 0.3s;
}
0 голосов
/ 11 сентября 2013

Я получил эту работу, установив max-height на none, получив высоту, заново установив max-height на рассчитанную высоту.Префектно работает для меня.Я получил эту работу для меню Accordeon, с <h5> в качестве переключателя, расширяющего <div> внутри <div>.

JS:

$('h5').click(function(e) {
  $(this).parent('div').addClass('temp_expanded');
  var getheight = ($(this).parent('div').find('div').height());
  $(this).parent('div').removeClass('temp_expanded');
  $(this).parent('div').find('div').css('max-height', getheight);
});

МЕНЬШЕ:

div {
> div {
    max-height: 0px;
    overflow: hidden;
    .transition(all 0.3s ease-in-out);
}

&.temp_expanded {
    > div {
        max-height: none;
    }
}
...