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

其他回答

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

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

您应该改用scaleY。

上一页{背景色:#eee;变换:缩放Y(0);变换原点:顶部;转变:转变0.26s;}p: 悬停~ul{变换:缩放Y(1);}<p>将此悬停</p><ul><li>咖啡</li><li>茶</li><li>牛奶</li></ul>

我在jsfiddle上制作了上述代码的供应商前缀版本,并将jsfiddl更改为使用scaleY而不是height。

编辑有些人不喜欢scaleY如何转换内容。如果这是一个问题,那么我建议使用剪辑。

上一页{剪辑:矩形(自动,自动,0,自动);位置:绝对;边距:-1rem 0;衬垫:.5rem;颜色:白色;背景色:rgba(0、0、0和0.8);过渡特性:剪辑;过渡时间:0.5s;过渡时间函数:立方贝塞尔(0.175、0.885、0.32、1.275);}h3:悬停~ul,h3:活性~ul,ul:悬停{剪辑:矩形(自动,自动,10rem,自动);}<h3>悬停在此处</h3><ul><li>此列表</li><li>被剪裁</li><li>剪辑过渡</li><li>将显示它</li></ul><p>一些文本。。。</p>

我结合了最大高度和负边距来实现这个动画。

我使用了最大高度:2000px,但如果需要,您可以将该值设置为更高的值。我为展开时的最大高度和折叠时的边距设置动画。

js部分只是点击,对于纯css解决方案,可以用:hover或checkbox替换。

到目前为止,我只能看到两个问题,

过渡时间有限。(我只添加了2次计时)如果在下拉列表折叠时再次单击,它将跳转。

这是结果

[…document.querySelectorAll('.ab')].forEach(包装器=>{wrapper.addEventListener('click',函数(){this.classList.tggle('active');});});* {边距:0;框大小调整:边框框;}.c文件{溢出:隐藏;}.个项目{宽度:100%;可见性:隐藏;最大高度:0;边距底部:-2000px;-webkit过渡:边缘0.6s立方bezier(1,0,1,1),最大高度0s 0.6s线性,可见性0s 0.6s直线;过渡:边缘0.6s立方贝塞尔(1,0,1,1),最大高度0.6s线性,可见性0.6s线性;}.项>*{填充:1rem;背景色:#ddd;-webkit过渡:背景色0.6s轻松;过渡:背景色0.6s轻松;}.items>*:悬停{背景色:#eee;}.ab文件{填充:1rem;光标:指针;背景:#eee;}.ab活动+.c.项目{最大高度:2000px;边距底部:0;可见性:可见;-webkit过渡:最大高度0.6s立方bezier(1,0,1,1);过渡:最大高度0.6s立方bezier(1,0,1,1);}下拉列表{右边距:1rem;}.包装器{显示:-webkit框;显示:柔性;}<div class=“wrapper”><div class=“下拉列表”><div class=“ab”>仅文本</div><div class=“ab”>仅文本</div><div class=“ab”>下拉列表</div><div class=“c”><div class=“items”><p>项目</p><p>项目</p><p>项目asl;dk l;卡斯尔;d sa;lk语言</p><p>项目sal;千分之三</p><p>项目</p></div></div><div class=“ab”>仅文本</div><div class=“ab”>仅文本</div></div><div class=“下拉列表”><div class=“ab”>下拉列表</div><div class=“c”><div class=“items”><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p><p>项目</p></div></div><div class=“ab”>text</div></div><div class=“下拉列表”><div class=“ab”>占位符</div><div class=“ab”>下拉列表</div><div class=“c”><div class=“items”><p>项目</p><p>项目</p></div></div><div class=“ab”>占位符</div><div class=“ab”>占位符</div><div class=“ab”>占位符</div></div></div><h1>要推送的文本</h1>

这并不是问题的“解决方案”,而是一种变通方法。它只在用文本编写时有效,但可以根据需要更改为使用其他元素。

.originalContent {
    font-size:0px;
    transition:font-size .2s ease-in-out;
}
.show { /* class to add to content */
    font-size:14px;
}

下面是一个示例:http://codepen.io/overthemike/pen/wzjRKa

本质上,您将字体大小设置为0,并以足够快的速度将其转换为所需的高度,而不是高度、最大高度或scaleY()等。用CSS将实际高度转换为auto目前是不可能的,但转换内容是可能的,因此字体大小转换。

注意-代码笔中有javascript,但它的唯一目的是在手风琴上单击时添加/删除css类。这可以通过隐藏的单选按钮来完成,但我并没有专注于此,只是高度转换。

具有行高、填充、不透明度和边距的可选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>