我正在尝试使用CSS转换制作一个<ul>幻灯片。

<ul>开始于高度:0;。悬停时,高度设置为height:auto;。然而,这导致它简单地出现,

如果我从高度做:40px;至高度:自动;,那么它将向上滑动到高度:0;,然后突然跳到正确的高度。

如果不使用JavaScript,我怎么能做到这一点?

#子0{高度:0;溢出:隐藏;背景色:#dedede;-moz过渡:高度1s容易;-webkit过渡:高度1s轻松;-o过渡:高度1s容易;过渡:高度1s;}#parent0:悬停#child0{高度:自动;}#孩子40{高度:40px;溢出:隐藏;背景色:#dedede;-moz过渡:高度1s容易;-webkit过渡:高度1s轻松;-o过渡:高度1s容易;过渡:高度1s;}#parent40:悬停#child40{高度:自动;}h1小时{字号:粗体;}两个CSS片段之间的唯一区别是一个高度为0,另一个高度是40。<小时><div id=“parent0”><h1>将我悬停(高度:0)</h1><div id=“child0”>一些内容<br>一些内容<br>一些内容<br>一些内容<br>一些内容<br>一些内容<br></div></div><小时><div id=“parent40”><h1>将我悬停(高度:40)</h1><div id=“child40”>一些内容<br>一些内容<br>一些内容<br>一些内容<br>一些内容<br>一些内容<br></div></div>


当前回答

使用CSS3过渡设置高度动画的一个视觉解决方法是设置填充动画。

你不太能得到完全的擦除效果,但在过渡持续时间和填充值之间进行切换应该会让你足够接近。如果您不想显式设置高度/最大高度,这应该是您想要的。

div {
    height: 0;
    overflow: hidden;
    padding: 0 18px;
    -webkit-transition: all .5s ease;
       -moz-transition: all .5s ease;
            transition: all .5s ease;
}
div.animated {
    height: auto;
    padding: 24px 18px;
}

http://jsfiddle.net/catharsis/n5XfG/17/(从jsFiddle上方的stephband上重复)

其他回答

当我发布这篇文章时,已经有30多个答案了,但我觉得我的答案比杰克已经接受的答案要好。

我对简单地使用最大高度和CSS3转换产生的问题并不满意,因为正如许多评论人士所指出的,你必须将最大高度值设置得非常接近实际高度,否则会延迟。有关该问题的示例,请参阅此JSFiddle。

为了解决这个问题(虽然仍然不使用JavaScript),我添加了另一个转换转换的HTML元素:translateY CSS值。

这意味着同时使用了max-height和translateY:max-heith允许元素向下推它下面的元素,而translateY提供了我们想要的“即时”效果。最大高度的问题仍然存在,但其影响有所减弱。这意味着你可以为你的最大高度值设置一个更大的高度,而不用担心它。

总的好处是,在转换回(塌陷)时,用户可以立即看到translateY动画,因此最大高度需要多长时间并不重要。

解决方案为Fiddle

正文{字体系列:无衬线;}.切换{位置:相对;边框:2px实心#333;边界半径:3px;边距:5px;宽度:200px;}.切换标题{边距:0;填充:10px;背景色:#333;颜色:白色;文本对齐:居中;光标:指针;}.拨动高度{背景色:番茄;溢出:隐藏;过渡:最大高度。6s轻松;最大高度:0;}.tggle:悬停.tggle高度{最大高度:1000px;}.tggle转换{填充:5px;颜色:白色;转换:转换。4s轻松;变换:translateY(-100%);}.tggle:悬停.tggle变换{变换:translateY(0);}<div class=“toggle”><div class=“toggle header”>切换!</div><div class=“toggle height”><div class=“toggle transform”><p>内容</p><p>内容</p><p>内容</p><p>内容</p></div></div></div><div class=“toggle”><div class=“toggle header”>切换!</div><div class=“toggle height”><div class=“toggle transform”><p>内容</p><p>内容</p><p>内容</p><p>内容</p></div></div></div>

要从任何起始高度(包括0)过渡到自动(全尺寸和灵活),而不需要基于每个节点的硬设置代码或任何用户代码来初始化:https://github.com/csuwildcat/transition-auto.

您想要的:http://codepen.io/csuwldcat/pen/kwsdF

将以下JS文件插入页面,然后从要展开和收缩的节点中添加/删除一个布尔属性--reveal=“”。

作为用户,一旦包含示例代码下面的代码块:

/*** Nothing out of the ordinary in your styles ***/

<style>
    div {
        height: 0;
        overflow: hidden;
        transition: height 1s;
    }
</style>

/*** Just add and remove one attribute and transition to/from auto! ***/

<div>
    I have tons of content and I am 0px in height you can't see me...
</div>

<div reveal>
     I have tons of content and I am 0px in height you can't see me...
     but now that you added the 'reveal' attribute, 
     I magically transitioned to full height!...
</div>

将此JS文件放到页面中:

/*** Code for height: auto; transitioning ***/

(function(doc){

/* feature detection for browsers that report different values for scrollHeight when an element's overflow is hidden vs visible (Firefox, IE) */
var test = doc.documentElement.appendChild(doc.createElement('x-reveal-test'));
    test.innerHTML = '-';
    test.style.cssText = 'display: block !important; height: 0px !important; padding: 0px !important; font-size: 0px !important; border-width: 0px !important; line-height: 1px !important; overflow: hidden !important;';
var scroll = test.scrollHeight || 2;
doc.documentElement.removeChild(test);

var loading = true,
    numReg = /^([0-9]*\.?[0-9]*)(.*)/,
    skipFrame = function(fn){
      requestAnimationFrame(function(){
        requestAnimationFrame(fn);
      });
    },
    /* 2 out of 3 uses of this function are purely to work around Chrome's catastrophically busted implementation of auto value CSS transitioning */
    revealFrame = function(el, state, height){
        el.setAttribute('reveal-transition', 'frame');
        el.style.height = height;
        skipFrame(function(){
            el.setAttribute('reveal-transition', state);
            el.style.height = '';
        });
    },
    transitionend = function(e){
      var node = e.target;
      if (node.hasAttribute('reveal')) {
        if (node.getAttribute('reveal-transition') == 'running') revealFrame(node, 'complete', '');
      } 
      else {
        node.removeAttribute('reveal-transition');
        node.style.height = '';
      }
    },
    animationstart = function(e){
      var node = e.target,
          name = e.animationName;   
      if (name == 'reveal' || name == 'unreveal') {
        
        if (loading) return revealFrame(node, 'complete', 'auto');
        
        var style = getComputedStyle(node),
            offset = (Number(style.paddingTop.match(numReg)[1])) +
                     (Number(style.paddingBottom.match(numReg)[1])) +
                     (Number(style.borderTopWidth.match(numReg)[1])) +
                     (Number(style.borderBottomWidth.match(numReg)[1]));
                     
        if (name == 'reveal'){
          node.setAttribute('reveal-transition', 'running');
          node.style.height = node.scrollHeight - (offset / scroll) + 'px';
        }
        else {
            if (node.getAttribute('reveal-transition') == 'running') node.style.height = '';
            else revealFrame(node, 'running', node.scrollHeight - offset + 'px');
        }
      }
    };

doc.addEventListener('animationstart', animationstart, false);
doc.addEventListener('MSAnimationStart', animationstart, false);
doc.addEventListener('webkitAnimationStart', animationstart, false);
doc.addEventListener('transitionend', transitionend, false);
doc.addEventListener('MSTransitionEnd', transitionend, false);
doc.addEventListener('webkitTransitionEnd', transitionend, false);

/*
    Batshit readyState/DOMContentLoaded code to dance around Webkit/Chrome animation auto-run weirdness on initial page load.
    If they fixed their code, you could just check for if(doc.readyState != 'complete') in animationstart's if(loading) check
*/
if (document.readyState == 'complete') {
    skipFrame(function(){
        loading = false;
    });
}
else document.addEventListener('DOMContentLoaded', function(e){
    skipFrame(function(){
        loading = false;
    });
}, false);

/* Styles that allow for 'reveal' attribute triggers */
var styles = doc.createElement('style'),
    t = 'transition: none; ',
    au = 'animation: reveal 0.001s; ',
    ar = 'animation: unreveal 0.001s; ',
    clip = ' { from { opacity: 0; } to { opacity: 1; } }',
    r = 'keyframes reveal' + clip,
    u = 'keyframes unreveal' + clip;

styles.textContent = '[reveal] { -ms-'+ au + '-webkit-'+ au +'-moz-'+ au + au +'}' +
    '[reveal-transition="frame"] { -ms-' + t + '-webkit-' + t + '-moz-' + t + t + 'height: auto; }' +
    '[reveal-transition="complete"] { height: auto; }' +
    '[reveal-transition]:not([reveal]) { -webkit-'+ ar +'-moz-'+ ar + ar +'}' +
    '@-ms-' + r + '@-webkit-' + r + '@-moz-' + r + r +
    '@-ms-' + u +'@-webkit-' + u + '@-moz-' + u + u;

doc.querySelector('head').appendChild(styles);

})(document);

/*** Code for DEMO ***/

    document.addEventListener('click', function(e){
      if (e.target.nodeName == 'BUTTON') {
        var next = e.target.nextElementSibling;
        next.hasAttribute('reveal') ? next.removeAttribute('reveal') : next.setAttribute('reveal', '');
      }
    }, false);

你可以,用一点非语义的小把戏。我通常的方法是设置外部DIV的高度动画,该外部DIV有一个子级,这是一个仅用于测量内容高度的无样式DIV。

函数growDiv(){var growDiv=文档.getElementById('grow');if(growtDiv.clientHeight){growtDiv.style.height=0;}其他{var wrapper=document.querySelector('.measureingWrapper');growDiv.style.height=wrapper.clientHeight+“px”;}}#成长{-moz过渡:高度.5s;-ms过渡:高度.5s;-o过渡:高度.5s;-webkit过渡:高度.5s;过渡:高度.5s;高度:0;溢出:隐藏;轮廓:1px纯红色;}<input type=“button”onclick=“growDiv()”value=“grow”><div id='grow'><div class='measureingWrapper'><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div></div></div>

人们希望能够省去.metringWrapper,只需将DIV的高度设置为auto并设置动画,但这似乎不起作用(设置了高度,但没有动画发生)。

函数growDiv(){var growDiv=文档.getElementById('grow');if(growtDiv.clientHeight){growtDiv.style.height=0;}其他{growDiv.style.height=“自动”;}}#成长{-moz过渡:高度.5s;-ms过渡:高度.5s;-o过渡:高度.5s;-webkit过渡:高度.5s;过渡:高度.5s;高度:0;溢出:隐藏;轮廓:1px纯红色;}<input type=“button”onclick=“growDiv()”value=“grow”><div id='grow'><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div><div>我部门的内容。</div></div>

我的解释是,动画运行需要明确的高度。当高度(起始高度或结束高度)为自动时,无法获得高度动画。

Jake的最大高度解决方案效果很好,如果硬编码提供的最大高度值不比实际高度大多少(因为否则会出现不期望的延迟和定时问题)。另一方面,如果硬编码值意外为不大于实际高度,元件将不会完全打开。

以下仅限CSS的解决方案还需要硬编码大小应大于大多数实际尺寸。然而,这如果实际大小在某些情况下大于硬编码大小。在这种情况下,转换可能会跳一点,但它永远不会留下部分可见的元素。因此,该解决方案也可用于未知内容,例如数据库,您只需知道内容通常不会更大超过x像素,但也有例外。

想法是使用负值作为边距底部(或边距顶部用于稍微不同的动画),并将内容元素放置到带溢出的中间元素:隐藏。内容的负边距因此减小了中间元件的高度。

以下代码使用边距底部从-150px到0倍。只要内容元素不是高于150px。此外,它使用最大高度上的过渡中间元素从0px到100%。这最终隐藏了中间元素如果内容元素高于150px。对于最大高度,过渡仅用于延迟其应用关闭时一秒钟,而不是为了平滑的视觉效果(因此它可以从0px运行到100%)。

CSS:

.content {
  transition: margin-bottom 1s ease-in;
  margin-bottom: -150px;
}
.outer:hover .middle .content {
  transition: margin-bottom 1s ease-out;
  margin-bottom: 0px
}
.middle {
  overflow: hidden;
  transition: max-height .1s ease 1s;
  max-height: 0px
}
.outer:hover .middle {
  transition: max-height .1s ease 0s;
  max-height: 100%
}

HTML格式:

<div class="outer">
  <div class="middle">
    <div class="content">
      Sample Text
      <br> Sample Text
      <br> Sample Text
      <div style="height:150px">Sample Test of height 150px</div>
      Sample Text
    </div>
  </div>
  Hover Here
</div>

边距底部的值应为负值,并尽可能接近可能达到内容元素的实际高度。如果是绝对的值)越大,则存在与最大高度解决方案,但只要硬编码的大小并不比实际大小大多少。如果绝对值边距底部的值小于变换有点跳跃。在任何情况下,过渡后内容元素被完全显示或完全移除。

有关详细信息,请参阅我的博客文章http://www.taccgl.org/blog/css_transition_display.html#combined_height

具有行高、填充、不透明度和边距的可选CSS解决方案:

正文{背景色:亚麻;}主要的,主要的{背景色:白色;}[id^=“toggle_”]~.content{线条高度:0;不透明度:0;填充:0.5雷姆;过渡:.2s缓和;}[id^=“toggle_”]~.content>p{边距:0;过渡:.2s缓和;}[id^=“toggle_”]:选中~.content{不透明度:1;衬垫:.5rem;线高:1.5;}[id^=“toggle_”]:选中~.content p{边距底部:.75rem;}[id^=“toggle_”]+标签{显示:柔性;调整内容:间距;衬垫:0.5em 1em;背景:灯光转向蓝;边框底部:1px实心灰色;光标:指针;}[id^=“toggle_”]+标签:之前{content:“显示”;}[id^=“toggle_”]:选中+标签:之前{content:“隐藏”;}[id^=“toggle_”]+标签:之后{内容:“\25BC”;}[id^=“toggle_”]:选中+标签:之后{内容:“\25B2”;}<main><div><input type=“checkbox”id=“toggle_1”隐藏><label for=“toggle_1”hidden></label><div class=“content”><p>Lorem ipsum dolor坐amet,consectetur adipiscing elit。Duis dolor neque,准将leo ut,拍卖人tincidunt mauris。Nunc frigilla tincidunt metus,非孕妇lorem调味品非。Duis ornare purus nisl,位于埃格特拱门。整数lorem ante,porta vulputate dui ut,blandit tempor tellus。Proin facilisis bibendum直径,位于调味品中。Donec volutpat dui eu mollis vulputate。Nunc commodo lobortis Nunc at ultrices。吊耳中的吊耳直径。</p></div></div><div><input type=“checkbox”id=“toggle_2”隐藏><label for=“toggle_2”hidden></label><div class=“content”><p>我不能坐在拍卖行旁边。Vivamus sed nisi vite nibh调味品pulvinar eu vel lorem。生命的前阶段是一个非常容易的阶段。在外的大型流苏。做一个临时自由人。Donec sapien libero,lacinia sed aliquet ut,imperite finibus tellus。努克·泰勒斯·莱图斯,波苏雷侯爵的朗库斯,坦普斯坐在埃尼姆。Morbi等人使用了一种边缘数字丝绒。Donec commodo,est id accumsan cursus,diam dui hendrerit nisi,vel hendreritpurus dolor ut risus。Phasellus mattis egestas ipsum sed ullamcorper。在直径舌中,rhoncus vel enim et,impredite porta justo。Curabitur vulputate hendrerit nisl,et ultricies diam.Maecenas ac leo a diam cursus ornare nec eu quam。</p><p>Sed非vulputate purus,Sed consectetur odio。Sed non-nih frigilla,impressive odio nec,efficitur ex.Suspendiss ut dignissim enim。迈塞纳斯·费利斯·奥古斯特(Maecenas felis augus),坐在埃米特·塞姆·费利利亚(sem frigilla)上,坐在艾姆桑·费利利亚的笔尖上。Quisque posuere lacus tortor,ques malesuada magna elementum a.Nullam id purus in pre terstie tincidunt。Morbi luctus orci eu egestas dignissim。Sed tincidunt,libero quis scelerisque bibendum,ligula nisi gravida libero,id lacinia nulla leo in elit。</p><p>Aenean aliquam risus id consectetur sagitis。Aliquam Aliquam nisl eu预示着诅咒,意味着最大的痛苦。Aliquam ipsum dolor,tempor et justo ac,fermentum mattis dui。伊蒂安在波苏雷舌。Vestibulum tortor metus,viverra vitae mi non,laoret iaculis purus。Praesent vel semper笔尖。Curabitur一只刚果拉库斯。在et pellentesque lorem。Morbi posuere猫科动物,无直径壳核,无壳核。Vivamus ultricies、massa id sagitis consequat、sem mauris tincidunt nunc、eu vehicula augus quam ut mauris。</p></div></div><div><input type=“checkbox”id=“toggle_3”hidden><label for=“toggle_3”hidden></label><div class=“content”><p>Lorem ipsum dolor坐amet,consectetur adipiscing elit。Duis dolor neque,准将leo ut,拍卖人tincidunt mauris。Nunc frigilla tincidunt metus,非孕妇lorem调味品非。Duis ornare purus nisl,位于埃格特拱门。整数lorem ante,porta vulputate dui ut,blandit tempor tellus。Proin facilisis bibendum直径,位于调味品中。Donec volutpat dui eu mollis vulputate。Nunc commodo lobortis Nunc at ultrices。吊耳中的吊耳直径。</p><p>Sed非vulputate purus,Sed consectetur odio。Sed non-nih frigilla,impressive odio nec,efficitur ex.Suspendiss ut dignissim enim。迈塞纳斯·费利斯·奥古斯特(Maecenas felis augus),坐在埃米特·塞姆·费利利亚(sem frigilla)上,坐在艾姆桑·费利利亚的笔尖上。Quisque posuere lacus tortor,ques malesuada magna elementum a.Nullam id purus in pre terstie tincidunt。Morbi luctus orci eu egestas dignissim。Sed tincidunt,libero quis scelerisque bibendum,ligula nisi gravida libero,id lacinia nulla leo in elit。</p></div></div></main>