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


当前回答

我理解这个问题需要一个没有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>

其他回答

我一直使用的解决方案是先淡出,然后缩小字体大小、填充和边距值。它看起来不像擦拭器,但它没有静态高度或最大高度。

工作示例:

/*最终显示器*/#菜单#列表{边距:.5em 1em;填充:1em;}/*隐藏,隐藏*/#menu:not(:hover)#列表{字体大小:0;边距:0;不透明度:0;填充:0;/*淡出,然后收缩*/过渡:不透明度.25s,字体大小.5s.25s,余量.5s.25s,填充.5s.25s;}/*显示*/#菜单:悬停#列表{/*取消闪烁,然后淡入*/过渡:字体大小.25s,边距.25s,填充.25s,不透明度.5s.25s;}<div id=“menu”><b>悬停我</b><ul id=“list”><li>项目</li><li>项目</li><li>项目</li><li>项目</li><li>项目</li></ul></div><p>另一段</p>

当我发布这篇文章时,已经有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);

扩展@jake的答案,过渡将一直到最大高度值,从而产生极快的动画效果-如果您同时设置了悬停和关闭两种过渡,则可以进一步控制疯狂的速度。

因此,li:hover是指鼠标进入状态,然后非悬停属性上的转换将是鼠标离开。

希望这会有所帮助。

例如:

.sidemenu li ul {
   max-height: 0px;
   -webkit-transition: all .3s ease;
   -moz-transition: all .3s ease;
   -o-transition: all .3s ease;
   -ms-transition: all .3s ease;
   transition: all .3s ease;
}
.sidemenu li:hover ul {
    max-height: 500px;
    -webkit-transition: all 1s ease;
   -moz-transition: all 1s ease;
   -o-transition: all 1s ease;
   -ms-transition: all 1s ease;
   transition: all 1s ease;
}
/* Adjust speeds to the possible height of the list */

这是一把小提琴:http://jsfiddle.net/BukwJ/

您可以从height:0转换到height:auto,前提是您还可以提供最小高度和最大高度。

div.stretchy{
    transition: 1s linear;
}

div.stretchy.hidden{
    height: 0;
}

div.stretchy.visible{
    height: auto;
    min-height:40px;
    max-height:400px;
}