我正在尝试使用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>


当前回答

我的解决方法是将最大高度转换为精确的内容高度,以获得流畅的动画效果,然后使用transitionEnd回调将最大高度设置为9999px,以便内容可以自由调整大小。

var content=$('#content');content.inner=$('#content.inter');//关闭时需要获取内容大小的内部div//css转换回调content.on('transitionEnd-webkitTransitionEnd transitiononend oTransitionEnd-msTransitionEnd',函数(e){if(content.hasClass('open')){content.css('max-height',9999);//尝试将此设置为“无”。。。我敢你!}});$('#toggle').on('click',函数(e){content.tggleClass(“打开关闭”);content.contentHeight=content.outerHeight();if(content.hasClass('closed')){//禁用转换&将最大高度设置为内容高度content.removeClass('transitions').css('max-height',content.contentHeight);setTimeout(函数){//启用和启动转换content.addClass('转换').css({'最大高度':0,“不透明度”:0});}, 10); // 10ms超时是禁用/启用转换的秘密因素//chrome只需要1ms,但FF需要约10ms,否则会在第一部动画中因某种原因而窒息}否则如果(content.hasClass('open')){content.contentHeight+=content.inter.outerHeight();//如果已关闭,请将内部高度添加到内容高度内容.css({'max height':content.contentHeight,“不透明度”:1});}});.转换{过渡:所有0.5秒都是缓进缓出;-webkit转换:所有0.5s都易于输入输出;-moz转换:所有0.5s都易于输入输出;}正文{字体系列:Arial;线高:3ex;}代码{显示:内联块;背景:#fafafa;填充:0 1ex;}#切换{显示:块;填充:10px;边距:10px自动;文本对齐:居中;宽度:30ex;}#内容{溢出:隐藏;边距:10px;边框:1px实心#666;背景:#efefef;不透明度:1;}#内容。内部{填充:10px;溢出:自动;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js“></script><div id=“content”class=“open”><div class=“inner”><h3>在<code>height:0</code>和<code>high:auto</code>之间平滑CSS转换</h3><p>一个巧妙的解决方法是使用<code>max-height</code>而不是<code>height</code>,并将其设置为比内容更大的值。问题是浏览器使用此值来计算过渡持续时间。因此,如果您将其设置为<code>max-height:1000px</code>,但内容只有100px高,则动画将快10倍</p><p>另一种选择是使用JS测量内容高度,并转换到固定值,但如果内容发生变化,则必须跟踪内容并手动调整其大小</p><p>此解决方案是两种转换的混合,即转换到测量的内容高度,然后在转换后将其设置为<code>最大高度:9999px</code>,以调整流体内容大小</p></div></div><br/><button id=“toggle”>接受挑战</按钮>

其他回答

杰克对最大高度动画化的回答很好,但我发现设置大的最大高度所导致的延迟很烦人。

可以将可折叠内容移动到内部div中,并通过获取内部div的高度来计算最大高度(通过JQuery,它将是outerHeight())。

$('button').bind('click', function(e) { 
  e.preventDefault();
  w = $('#outer');
  if (w.hasClass('collapsed')) {
    w.css({ "max-height": $('#inner').outerHeight() + 'px' });
  } else {
    w.css({ "max-height": "0px" });
  }
  w.toggleClass('collapsed');
});

这里有一个jsfiddle链接:http://jsfiddle.net/pbatey/duZpT

这里有一个jsfiddle,它提供了所需的绝对最小代码量:http://jsfiddle.net/8ncjjxh8/

要从任何起始高度(包括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);

我理解这个问题需要一个没有JavaScript的解决方案。但对于那些感兴趣的人来说,这里是我的解决方案,只使用了一点点JS。

好的,因此默认情况下高度将更改的元素的css设置为height:0;打开高度时:自动;。它也有过渡:高度;。但当然,问题是它不会从高度转换到高度:自动;

因此,我所做的是在打开或关闭时将高度设置为元素的scrollHeight属性。这种新的内联样式将具有更高的特异性,并覆盖两种高度:auto;高度:0;并且过渡运行。

打开时,我添加了一个transitioned事件侦听器,它将只运行一次,然后删除内联样式,将其设置为height:auto;这将允许元素在必要时调整大小,就像在这个更复杂的子菜单示例中一样https://codepen.io/ninjabonsai/pen/GzYyVe

关闭时,我会在下一个事件循环循环后立即使用setTimeout删除内联样式,而不会延迟。这意味着高度:自动;被临时覆盖,这允许转换回高度0;

const showHideElement=(元素,打开)=>{element.style.height=element.scrollHeight+“px”;element.classList.tggle(“打开”,打开);if(打开){element.addEventListener('transitionnend',()=>{element.style.removeProperty('height');}, {一次:真});}其他{window.setTimeout(()=>{element.style.removeProperty('height');});}}const menu=document.body.querySelector(“#menu”);const list=document.body.querySelector(“#menu>ul”)menu.addEventListener('useenter',()=>showHideElement(列表,true));menu.addEventListener('useleave',()=>showHideElement(list,false));#菜单>ul{高度:0;溢出:隐藏;背景色:#999;过渡:高度。25s缓和;}#菜单>ul.open{高度:自动;}<div id=“menu”><a>悬停我</a><ul><li>项目</li><li>项目</li><li>项目</li><li>项目</li><li>项目</li></ul></div>

无硬编码值。

没有JavaScript。

无近似值。

诀窍是使用隐藏和复制的div让浏览器了解100%的含义。

每当您能够复制要设置动画的元素的DOM时,此方法都适用。

.外部{边框:红色虚线1px;位置:相对;}.虚拟{可见性:隐藏;}.真实{位置:绝对;背景:黄色;高度:0;过渡:高度0.5s;溢出:隐藏;}.outer:悬停>.real{高度:100%;}将鼠标悬停在下面的框上:<div class=“outer”><!-- 要设置动画的实际元素--><div class=“real”>不可预测的内容不可预测内容不可预知内容不可预见内容不可预料内容不可预计内容不可预期内容不可预报内容不可预言内容内容不可预测内容不可预知内容</div><!-- 要设置动画的元素的精确副本。--><div class=“dummy”aria hidden=“true”>不可预测的内容不可预测内容不可预知内容不可预见内容不可预料内容不可预计内容不可预期内容不可预报内容不可预言内容内容不可预测内容不可预知内容</div></div>

编辑:向下滚动以获得更新的答案我在做一个下拉列表,看到了这篇文章。。。很多不同的答案,但我决定分享我的下拉列表。。。它并不完美,但至少它将只使用css进行下拉!我一直在使用transform:translateY(y)将列表转换为视图。。。你可以在测试中看到更多http://jsfiddle.net/BVEpc/4/ 我把div放在每一个li后面,因为我的下拉列表是从上到下的,为了正确地显示它们,这是需要的,我的div代码是:

#menu div {
    transition: 0.5s 1s;
    z-index:-1;
    -webkit-transform:translateY(-100%);
    -webkit-transform-origin: top;
}

并且悬停是:

#menu > li:hover div {
    transition: 0.5s;
    -webkit-transform:translateY(0);
}

因为ul高度设置为可以超过你身体内容的内容,所以我为ul做了这件事:

 #menu ul {
    transition: 0s 1.5s;
    visibility:hidden;
    overflow:hidden;
}

并悬停:

#menu > li:hover ul {
     transition:none;
     visibility:visible;
}

转换后的第二次是延迟,它将在我的下拉列表被动画关闭后隐藏。。。希望以后有人能从中受益。编辑:我真不敢相信人们真的使用了这个原型!此下拉菜单仅用于一个子菜单,仅此而已!!我更新了一个更好的,可以有两个子菜单,用于ltr和rtl方向,支持IE8。LTR的FiddleRTL的Fiddle希望将来有人会发现这很有用。