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


当前回答

根据MDN Web Docs,CSS转换规范中故意排除了auto值,因此在网格和柔性布局中使用height:100%、top或flex属性,而不是height:auto。

展开/折叠覆盖

.grid容器{显示:栅格;位置:绝对;}.内容{背景:浅绿色;高度:0;溢出:隐藏;过渡:1s;}span:hover+.gridcontainer.content{高度:100%;}<span>悬停在我上方</span><div class=“grid container”><div class=“content”>Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。在最低限度的威尼斯,quis nostrud exerciation ullamco labour nisi Ut aliquip ex a commo consequat。这是一个很好的例子。除了你偶尔犯下的错误外,你还得承担责任,这是因为你在实验室里表现得很糟糕</分区></div><p>其余页面内容</p>

展开/折叠滑动覆盖

.grid容器{显示:栅格;位置:绝对;溢出:隐藏;指针事件:无;/*以实现与容器下方元素的交互*/}.内容{背景:浅绿色;指针事件:自动;位置:相对;顶部:-100%;过渡:1s;}span:hover+.gridcontainer.content{顶部:0;}<span>悬停在我上方</span><div class=“grid container”><div class=“content”>Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。在最低限度的威尼斯,quis nostrud exerciation ullamco labour nisi Ut aliquip ex a commo consequat。这是一个很好的例子。除了你偶尔犯下的错误外,你还得承担责任,这是因为你在实验室里表现得很糟糕</分区></div><p>其余页面内容</p>

在文档流中展开/折叠

html格式{显示:栅格;}正文{显示:柔性;弯曲方向:柱;}.内容{背景:浅绿色;弹性基础:0;溢出:隐藏;过渡:1s;}span:悬停+内容{挠曲:1;}<span>悬停在我上方</span><div class=“content”>Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。在最低限度的威尼斯,quis nostrud exerciation ullamco labour nisi Ut aliquip ex a commo consequat。这是一个很好的例子。除了你偶尔犯下的错误外,你还得承担责任,这是因为你在实验室里表现得很糟糕</分区><p>其余页面内容</p>

其他回答

使用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上重复)

此解决方案使用了一些技术:

填充底部:100%“hack”,其中百分比是根据元素的当前宽度定义的。有关此技术的更多信息。浮动收缩包装,(需要额外的div来应用浮动清除黑客)非语义使用https://caniuse.com/#feat=css-编写模式和一些转换来撤销它(这允许在垂直上下文中使用上面的填充黑客)

结果是,我们只使用CSS实现了高性能的转换,并使用一个转换函数来平滑地实现转换;圣杯!

当然,这也有缺点!我无法确定如何控制内容被截断的宽度(溢出:隐藏);由于衬垫底部的裂缝,宽度和高度密切相关。不过,也许有办法,所以我们会回到过去。

https://jsfiddle.net/EoghanM/n1rp3zb4/28/

正文{填充:1em;}.触发器{字号:粗体;}/*.扩展器仅用于浮动清除*/.扩展器::之后{内容:“”;显示:表格;清晰:两者都有;}.外部{float:左;/*目的:收缩以适应内容*/边框:1px实心绿色;溢出:隐藏;}.内部{过渡:填充底部0.3s,方便进出;/*或者你能想出的任何疯狂的转换函数*/底部填充:0%;/*填充百分比是根据宽度定义的。此级别的宽度等于内容的高度*/高度:0;/*不幸的是,书写模式的改变还有其他的不良影响,比如光标的方向*/写入模式:垂直rl;光标:默认值;/*不需要垂直文本(横向工字梁)*/变换:旋转(-90度)平移X(-100%);/*撤消写入模式*/变换原点:0 0;边距:0;/*此处的左/右边距将增加高度*/}.inter>div{white-space:nowrap;}.extender:hover.intern,/*在展开时保持打开*/.t触发器:悬停+扩展器.内部{填充底部:100%;}<div class=“trigger”>HoverMe</div><div class=“扩展器”><div class=“outer”><div class=“inner”><div>第一项</div><div>内容</div><div>内容</div><div>内容</div><div>长内容不能宽于外部高度,不幸的是</div><div>最后一项</div></div></div></div><div>在内容之后</div></div>

下面是我刚刚与jQuery结合使用的解决方案。这适用于以下HTML结构:

<nav id="main-nav">
    <ul>
        <li>
            <a class="main-link" href="yourlink.html">Link</a>
            <ul>
                <li><a href="yourlink.html">Sub Link</a></li>
            </ul>
        </li>
    </ul>
</nav>

以及功能:

    $('#main-nav li ul').each(function(){
        $me = $(this);

        //Count the number of li elements in this UL
        var liCount = $me.find('li').size(),
        //Multiply the liCount by the height + the margin on each li
            ulHeight = liCount * 28;

        //Store height in the data-height attribute in the UL
        $me.attr("data-height", ulHeight);
    });

然后,您可以使用click函数使用css()设置和删除高度

$('#main-nav li a.main-link').click(function(){
    //Collapse all submenus back to 0
    $('#main-nav li ul').removeAttr('style');

    $(this).parent().addClass('current');

    //Set height on current submenu to it's height
    var $currentUl = $('li.current ul'),
        currentUlHeight = $currentUl.attr('data-height');
})

CSS:

#main-nav li ul { 
    height: 0;
    position: relative;
    overflow: hidden;
    opacity: 0; 
    filter: alpha(opacity=0); 
    -ms-filter: "alpha(opacity=0)";
    -khtml-opacity: 0; 
    -moz-opacity: 0;
    -webkit-transition: all .6s ease-in-out;
    -moz-transition: all .6s ease-in-out;
    -o-transition: all .6s ease-in-out;
    -ms-transition: all .6s ease-in-out;
    transition: all .6s ease-in-out;
}

#main-nav li.current ul {
    opacity: 1.0; 
    filter: alpha(opacity=100); 
    -ms-filter: "alpha(opacity=100)";
    -khtml-opacity: 1.0; 
    -moz-opacity: 1.0;
}

.ie #main-nav li.current ul { height: auto !important }

#main-nav li { height: 25px; display: block; margin-bottom: 3px }

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

仅限CSS的灵活高度解决方案

我偶然发现了一个使用灵活行为的奇怪解决方案。它至少适用于Chrome和Firefox。

首先,高度转换仅在0和100%之间有效,两个数值。由于“auto”不是数值,因此分数在0和“自动”之间不存在增量。100%是灵活的值,因此不需要特定高度。其次,隐藏内容的外部容器和内部容器都必须设置为display:flex with flex direction:column。第三,外部容器必须具有高度属性。仅当所有内容都包含在外部容器中时,将其设置为0才能保持平滑过渡,因为弯曲行为优先于高度。Edit:Json建议使用height:fit内容,这样容器下面的任何内容都会被向下推。

.外部容器{高度:0;显示:flex;flex方向:列;}.内部容器{display:flex;flex direction:column;}.隐藏内容{高度:0;不透明度:0;过渡:高度1s 0.5s进出,不透明度0.5s进出;/*过渡淡出:首先淡出不透明度,然后在延迟等于不透明度持续时间后收缩高度*/}.t触发器:悬停+.内部容器>.隐藏内容{高度:100%;不透明度:1;过渡:高度1s进出,不透明度0.5s 1s进出;/*过渡:首先展开高度,然后在等于高度持续时间的延迟后淡入不透明度*/}<div class=“outer container”><a href=“#”class=“trigger”>悬停以显示内部容器的隐藏内容</a><div class=“内部容器”><div class=“hidden content”>这是隐藏内容。当由悬停触发时,其高度从0过渡到100%,这会将同一容器中的其他内容逐渐向下推</分区><div>在同一个容器中,当隐藏内容的高度从0过渡到100%时,其他内容会逐渐向下推</分区></div></div>

按“运行代码段”按钮查看正在运行的转换。它只是CSS,没有特定的高度。