【问题标题】:CSS transition effect not workingCSS过渡效果不起作用
【发布时间】:2018-06-29 16:22:26
【问题描述】:

我在我正在开发的 wordpress 网站上创建了一个带有 javascript 的“阅读更多/阅读更少”可折叠按钮,用于作者的简历描述。

collapsable 工作正常,只是过渡 css 效果不起作用。我已经对此进行了测试,我认为这是因为当我展开文本时,我将高度设置为“自动”,因为显然我不知道文本将有多长。

如果我将高度设置为数字,则过渡有效。但我需要设置为自动。

这里是小提琴: https://jsfiddle.net/brsastre/jo29pfm8/

p {
  height: 30px;
    overflow: hidden;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}
p.uncollapsed {
  height: auto;
}

【问题讨论】:

    标签: css transition


    【解决方案1】:

    您不能在“自动”维度上设置动画(很遗憾)。 你应该使用高度来制作动画。 这是解决方案:

    p {
      height: 30px;
        overflow: hidden;
        -webkit-transition: all 0.5s ease;
        -moz-transition: all 0.5s ease;
        -o-transition: all 0.5s ease;
        transition: all 0.5s ease;
    }
    p.uncollapsed {
      height: 80px;
      -webkit-transition: all 0.5s ease;
      transition: all 0.5s ease;
    }
    

    【讨论】:

    • 谢谢马克,但不幸的是这个解决方案不起作用,因为我可以在加载页面时使用 javascript 获取高度,但是移动设备上的高度不同.. 当你缩小浏览器时,高度会增长。
    【解决方案2】:

    您不能转换到height: auto,最酷的技巧之一是为max-height 设置动画,以获得与height: auto 相同的效果。

    类似的东西:

    var button = document.getElementById("button");
    button.onclick = function() {
      var text = document.getElementById("text");
      text.classList.add("uncollapsed");
    };
    p {
      max-height: 30px;
      overflow: hidden;
      transition: max-height 0.5s ease;
    }
    
    p.uncollapsed {
      max-height: 100px;
    }
    <p id="text">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem obcaecati tenetur voluptates asperiores vero necessitatibus incidunt magni beatae debitis. Libero error, ab. Debitis odit, nulla blanditiis obcaecati assumenda eveniet. Nesciunt. Lorem
      ipsum dolor sit amet, consectetur adipisicing elit. Dolorem libero provident beatae qui minima iusto, corrupti quidem nam iste alias dicta? Cupiditate quidem neque dolores distinctio quam commodi inventore provident.
    </p>
    <button id="button">button</button>

    【讨论】:

    • 谢谢 Bhuwan - 我决定采用这个解决方案。不过我有个缺点。过渡看起来很古怪。就像,它打开很快,关闭需要几分之一秒......我认为这是因为它计算的过渡高度不真实。
    【解决方案3】:

    由于height: auto,这将不起作用。 试试这个:

    p {
       height: 30px;
       overflow: hidden;
       -webkit-transition: all 0.5s ease;
       -moz-transition: all 0.5s ease;
       -o-transition: all 0.5s ease;
       transition: all 0.5s ease;
    }
    
    p.uncollapsed {
      height: 100px;
    }
    

    【讨论】:

    • 谢谢马克,但不幸的是这个解决方案不起作用,因为我可以在加载页面时使用 javascript 获取高度,但是移动设备上的高度不同.. 当你缩小浏览器时,高度会增长。
    猜你喜欢
    • 2021-09-30
    • 2015-09-18
    • 1970-01-01
    • 2015-12-01
    • 2012-09-27
    • 2013-10-22
    相关资源
    最近更新 更多