CSS3在子元素中添加/移除类时的过渡动画

CSS3 transition animation when adding/removing class in child elements

本文关键字:动画 元素 添加 CSS3      更新时间:2023-09-26

我有一个问题,当添加类到父类时,CSS3过渡不能在子元素上工作。

下面是我的代码:http://jsfiddle.net/4zwg3/327/

图像没有动画,并立即变为50px高度

CSS:

.header {
  height: 400px;
  width: 400px;
  background: blue;
}
.small_header img {
    height: 50px;
    background-size: auto 100%;    
    -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}
.small_header {
    height: 100px;
    background-size: auto 100%;    
    -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}
HTML:

<div class="header">
<img src="http://www.codeproject.com/KB/GDI-plus/ImageProcessing2/img.jpg">
</div>
Javascript:

var click = 1;
$( ".header" ).on( "click", function() {
console.log('works');
    if (click == 1) {
        $(".header").addClass("small_header");
        $(".small_header").removeClass("big_header");
        click = 0;
    } else {
        $(".header").addClass("big_header");
        $(".small_header").removeClass("small_header");
        click = 1;
    }
});

但是你可以看到image.

没有过渡动画。

如何修复?

这个问题是因为图像没有任何开始高度,浏览器不能计算过渡,如果你在small_header类上添加过渡,过渡只在图像缩小时起作用。

$( ".header" ).on( "click", function() {
    $(".header").toggleClass("small_header");
});
.header {
  height: 400px;
  width: 400px;
  background: blue;
}
.header img {
  height:200px;
  -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}
.small_header img {
    height: 50px;
    background-size: auto 100%;    
}
.small_header {
    height: 100px;
    background-size: auto 100%;    
    -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<img src="http://www.codeproject.com/KB/GDI-plus/ImageProcessing2/img.jpg">
</div>

首先,我会避免处理这两个类和"click"变量。

你的JS应该看起来更像:

 $( ".header" ).on( "click", function() {
console.log('works');
$(".header").toggleClass("small");
});

你的CSS应该是这样的:

.header {
  height: 400px;
  width: 400px;
  background: blue;
}
.small {
    height: 100px;
    -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}
.small img {
    height: 50%;   
    -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}

试试:-

#someDiv{
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

它不能是动画,因为CSS不知道你的图像的起始大小。你应该为计算动画添加图像大小:

.header img {
    height: 400px;
}