如何使用 css3 为 div 制作动画

How to animate a div using css3

我有以下代码:

$('.div-1').on('click', function() {
  $('.block').addClass('animated');
});
$('.div-2').on('click', function() {
  $('.block2').addClass('animated');
});
html,
body {
  height: 100%;
}
.div-1 {
  display: inline-block;
  padding: 40px;
  background: tomato;
}
.div-2 {
  display: inline-block;
  padding: 40px;
  background: tan;
}
.block2 {
  background: green;
}
.animated {
  -webkit-animation: animateThis 0.2s ease;
  animation: animateThis 0.2s ease;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}
.block {
  background: red;
}
@-webkit-keyframes animateThis {
  0% {
    height: 0;
    width: 0;
  }
  100% {
    height: 100%;
    width: 100%;
  }
}
keyframes animateThis {
  0% {
    height: 0;
    width: 0;
  }
  100% {
    height: 100%;
    width: 100%;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-1"></div>
<div class="div-2"></div>

<section class="block"></section>
<section class="block2"></section>

这里有一个PEN

我想做的是:单击 div-1div-2 时,blockblock2 部分的相应动画应源自 div-1div-2 的底部中心 。它目前从 左角 .

开始动画

我的问题是:如何让动画源自 div-1div-2 底部中心 而不是 左角。此外,当单击 div-1div-2 时,当前打开的部分应该关闭(带有打开方式的反向动画)并且相应的单击 div 应该作为新动画打开。这如何通过脚本来完成?我不想使用外部库 (animate.css)。我已经尝试了几种方法来解决这个问题,但我不知道该怎么做,因为我无法理解逻辑。

如果你想像你问的那样调整动画的起点,你可以使用 transform-origin CSS 属性。 写

transform-origin: 50% 100%;
-webkit-transform-origin: 50% 100%;

使其从底部中心开始。

要使用反向动画,只需在动画指令后添加关键字 alternate。完成后会播放还原的动画

示例:

.animated {
  -webkit-animation: animateThis 0.2s ease alternate;
  animation: animateThis 0.2s ease alternate;
  -webkit-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}

使用单独的动画来隐藏方块

 @-webkit-keyframes shrinkThis {
      0% {
        height: 100%;
        width: 100%;
  }

  100% {
    height: 0;
    width: 0;
  }
} 

并且可以通过回调知道方块被隐藏然后展开对应的方块

$(".block").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", 
  function() {
      $('.block2').removeClass('shrink');
      $('.block2').addClass('expand');
      $('.block2').unbind();
  });

这里是PEN

定位编辑: 正如某人所指出的,您可以使用 transform-origin 。但它仅适用于缩放、平移等变换。

该块的 css 应该如下所示:

.block {
  /*background: red;*/
  position:absolute;
  border:solid 1px;
    height: 100%;
    width: 100%;
  transform-origin: 20px 0%;
-webkit-transform-origin: 20px 0%;
}

转换使用缩放而不是修改高度和宽度:

@-webkit-keyframes animateThis {
  0% {
    -webkit-transform: scale(0.1,0.1);
  }
  100% {
    -webkit-transform: scale(1,1);
  }
} 

这是更新后的 PEN

需要改进的地方:应该动态计算变换原点。