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


当前回答

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

其他回答

我只是为<li>元素设置动画,而不是为整个容器设置动画:

<style>
.menu {
    border: solid;
}
.menu ul li {
    height: 0px;
    transition: height 0.3s;
    overflow: hidden;
}
button:hover ~ .wrapper .menu ul li,
button:focus ~ .wrapper .menu ul li,
.menu:hover ul li {
    height: 20px;
}
</style>


<button>Button</button>
<div class="wrapper">
    <div class="menu">
        <ul>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
            <li>menuitem</li>
        </ul>
    </div>
</div>

您可以添加ul:margin 0;高度为0。

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

可以将可折叠内容移动到内部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/

我使用的方法是基于字体大小(使用em作为单位)或至少是影响我们想要动画的框的垂直大小的所有内容。然后,如果有任何东西不是以em为单位(例如1px边框),我会在框关闭时将其设置为0,并将所有子对象设置为*。

动画动画显示的是从0到100的字体大小(%)。什么?父级的已知字体大小。

它工作的规则是,动画框中的所有内容必须:

对所有字体大小和行高使用%将em用于所有垂直方向(如高度、边距和顶部/底部填充等)如果将px用于垂直的内容(例如,边框顶部/底部),则在框关闭时应覆盖该内容(例如:边框顶部:0;边框底部:0;)

在某种程度上,您仍然可以使用像素作为参考单位,只需将包装字体大小设置为100px,例如#page{font-size:100px;},因此如果您希望在内部任何地方使用10px,则可以使用0.1em。

这不是任何人都能写的最漂亮的东西,但嘿,这些浏览器并不能为我们提供任何解决这个问题的漂亮方案。一旦箱子的高度无法预测,我们别无选择,只能弄得有些脏,这是我想到的最不脏的东西。

悬停版本:

https://jsfiddle.net/xpsfkb07/1/

#第页{字体大小:calc((35vw+65vh)/30);/*只是一些响应性设计作为奖励*/}#滑动轴承箱{背景色:#e8e8e8;可见性:隐藏;字号:0;/*从0到100%设置动画*/不透明度:0;/*可选的*/过渡:0.5s;}a#ahover:悬停~#slidebox{可见性:可见;字体大小:100%;/*从0到100%设置动画*/不透明度:1;/*可选的*/}a#ahover:not(:hover)~#slidebox*{边框顶部:0;边框底部:0;/*在这里放置任何以像素为单位的垂直线,在本例中为边框*/}a#按钮{显示:内联flex;对齐项目:居中;对齐内容:中心;位置:相对;宽度:20em;高度:3em;填充:0.5em;边框:2px实心#0080ff;边界半径:0.4em;背景色:#8fbfef;颜色:#404040;框大小调整:边框框;}#某种形式的{页边距:1em;边距底部:1em;填充:1 m 4 m 1 m 4 mm;背景色:#d8ffd8;边框:1px实心#888888;}#某种形式的输入{显示:内联块;框大小调整:边框框;字体大小:125%;填充:0.5em;宽度:50%;/*任何水平的都可以是px或%*/边界半径:0.4em;边框:1px纯红色;}<div id=page><a id=ahover href=“#”>悬停我</a><br>下面是滑动框:<div id=slidebox>我是幻灯片框的内容(第1行)<br>我是幻灯片框的内容(第2行)<br><a id=button href=“#”>我是幻灯片框中的某个按钮</a><br>我是幻灯片框的内容(第3行)<br>我是幻灯片框的内容(第4行)。<div id=someform>一个有表格的盒子<br><输入类型=文本值=“文本框”></div>我是幻灯片框的内容(第5行)<br>我是幻灯片框的内容(第6行)。</div>这是在盒子后面。</div>

类别更改版本:

https://jsfiddle.net/8xzsrfh6/

const switch_ele=文档.getElementById('aclass');switch_ele.addEventListener('click',函数(){const box_ele=文档.getElementById('slidebox');box_ele.className=box_ele_className=='显示'?'hide':'显示';},true);#第页{字体大小:calc((35vw+65vh)/30);/*只是一些响应性设计作为奖励*/}#滑动轴承箱{背景色:#e8e8e8;可见性:隐藏;字号:0;/*从0到100%设置动画*/不透明度:0;/*可选的*/转换:.5s;}#幻灯片放映{可见性:可见;字体大小:100%;/*从0到100%设置动画*/不透明度:1;/*可选的*/}#幻灯片隐藏*{边框顶部:0;边框底部:0;/*在这里放置任何以像素为单位的垂直线,在本例中为边框*/}a#按钮{显示:内联flex;对齐项目:居中;对齐内容:中心;位置:相对;宽度:20em;高度:3em;填充:0.5em;边框:2px实心#0080ff;边界半径:0.4em;背景色:#8fbfef;颜色:#404040;框大小调整:边框框;}#某种形式的{页边距:1em;边距底部:1em;填充:1 m 4 m 1 m 4 mm;背景色:#d8ffd8;边框:1px实心#888888;}#某种形式的输入{显示:内联块;框大小调整:边框框;字体大小:125%;填充:0.5em;宽度:50%;/*任何水平的都可以是px或%*/边界半径:0.4em;边框:1px纯红色;}<div id=page><a id=aclass href=“#”>开关类w/js</a><br>下面是滑动框:<div id=slidebox class=hide>我是幻灯片框的内容(第1行)<br>我是幻灯片框的内容(第2行)<br><a id=button href=“#”>我是幻灯片框中的某个按钮</a><br>我是幻灯片框的内容(第3行)<br>我是幻灯片框的内容(第4行)。<div id=someform>一个有表格的盒子<br><输入类型=文本值=“文本框”></div>我是幻灯片框的内容(第5行)<br>我是幻灯片框的内容(第6行)。</div>这是在盒子后面。</div>

一句话解决方案:使用填充过渡。这对于大多数情况(如手风琴)来说已经足够了,甚至更好,因为填充值通常不大,所以速度很快。

如果希望动画过程更好,只需提高填充值即可。

parent{border top:#999 1px solid;}h1{margin:.5rem;字体大小:1.3rem}.儿童{高度:0;溢出:隐藏;背景色:#dedede;过渡:填充。2s易进易出,不透明度。2s容易进易出;填充:0.5雷姆;不透明度:0;}.childre::之前,.childres::之后{content:“”;显示:块;}.children::在{margin-top:-2rem;}之前.children::在{margin-bottom:-2rem;}之后.父级:悬停.子级{高度:自动;不透明度:1;衬垫:2.5雷姆。5雷姆;/*0.5+abs(-2),确保低于预期最小高度*/}<div class=“parent”><h1>将我悬停</h1><div class=“children”>一些内容<br>一些内容<br>一些内容<br>一些内容<br>一些内容<br>一些内容<br></div></div><div class=“parent”><h1>将我悬停(长内容)</h1><div class=“children”>一些内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br>部分内容<br></div></div><div class=“parent”><h1>悬停我(简短内容)</h1><div class=“children”>一些内容<br>一些内容<br>一些内容<br></div></div>

你可以,用一点非语义的小把戏。我通常的方法是设置外部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>

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