javascript - 如何用纯CSS动画实现slide down效果?

查看:174
本文介绍了javascript - 如何用纯CSS动画实现slide down效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

用纯CSS动画实现slide down想过几种思路:

1. 使用max-height top...配和transition

设置定宽

默认样式为
.more {
    -webkit-transition: max-height .35s ease-in-out;
     -moz-transition: max-height .35s ease-in-out;
    -o-transition: max-height .35s ease-in-out;
    transition: max-height .35s ease-in-out;
    max-height: 0;
    overflow: hidden;
}
.more.active {
    max-height: 1000px;
}

上面使用的固定的max-height,但是会影响动画效果,另外如果高度大于指定高度会显示不全,所以不能使用此方案。

通过JS动态设置max-height

之前尝试设置max-height:100%,但是无效。但是如何能够动态设置实际heightmax-height是个问题,目前我是通过获取元素的scrollHeight来设置为max-height,实现动画效果,但是需要js操作是不特别爽,这样的话我不如直接使用js动画库了。

目前我的实现代码(待改进):https://jsfiddle.net/godtail/...

2. 如果没好的方案就考虑使用js动画库来实现了。

所以如果有合适的js动画库也推荐下吧

期待解答,谢谢大家~

===== 补充下我最后的解决方案吧 =====
因为考虑到兼容性选择(包括IE8)使用JS动画,为了不引入新的animal库,使用了目前所用mootools-more自带的slide
效果如下:https://jsfiddle.net/godtail/...
简单看了下实现原理(因为目前项目用的版本为V1.4.5,所以看得是这个版本的代码)
关键的两个文件:Fx.Slide.jsFx.js

#Fx.Slide.js
/**
1. 使用wrapper包裹element
2. 如果是水平滑动,设置wrapper: width:0, overflow: hidden
    设置element动画为 margin-left:0 <-> - element.width
3. 如果是垂直滑动,设置wrapper: height: 0, overflow: hidden
    设置element动画为 margin-top:0 <-> - element.height;
*/
if (!wrapper) wrapper = new Element('div', {
  styles: styles
}).wraps(element);

#Fx.js
/**
负责动画的实现

每一个fps对应一个instance,每次执行对应的loop,loop依次调用动画队列的step
*/
var instances = {}, timers = {};

var loop = function(){
    var now = Date.now();
    for (var i = this.length; i--;){
        var instance = this[i];
        if (instance) instance.step(now);
    }
};

var pushInstance = function(fps){
    var list = instances[fps] || (instances[fps] = []);
    list.push(this);
    if (!timers[fps]) timers[fps] = loop.periodical(Math.round(1000 / fps), list);
};

var pullInstance = function(fps){
    var list = instances[fps];
    if (list){
        list.erase(this);
        if (!list.length && timers[fps]){
            delete instances[fps];
            timers[fps] = clearInterval(timers[fps]);
        }
    }
};

解决方案

.slide-down{
    width: 100px;
    height: 0;
    -webkit-transition: height 1s;
    -moz-transition: height 1s;
    -o-transition: height 1s;
    &.active{
        height: 100px;
    }
}

// 补充
由于高度不能固定,只能用animate中keyframes创建动画slideInDown
写了个demo,可以参考一下: https://jsfiddle.net/xiangry/...

这篇关于javascript - 如何用纯CSS动画实现slide down效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆