单击按钮将 div1 移出屏幕并将 div2 从顶部移至 20px 时出现弹跳动画效果

bouncing animation effect when click on button to move div1 out of screen and div2 to 20px from top

请帮忙提前谢谢...抱歉英语不好...想要在 div1 和 div2 上下移动时弹跳的动画效果

我做了 main div 其中有 2 div... div1 和 div2.

我想让它像,当有人点击按钮时。

那个时候 div1 应该随着动画从顶部慢慢移出屏幕(慢慢移出顶部屏幕)。

同时 div2 应该位于距离屏幕顶部 20px 的位置。

我已经设置了几乎所有的东西,但我无法给它一个动画效果,这也难怪为什么,但是过渡效果或任何不起作用的东西。如果可能的话,我想用 JavaScript 代码来做我较少使用 jQuery 等

我很乐意使用另一种方法,比如不用 margin-top 将 div1 移出屏幕,将 div2 移到顶部,如果您推荐任何其他方法 css 或 javascript,没关系。我只想要 div1 和 div2 慢慢移动到顶部的动画效果。

function myFunction1() {
    document.getElementById("div1").style.marginTop = "-110px";
    document.getElementById("div2").style.marginTop = "20px";
}

function myFunction2() {
    document.getElementById("div1").style.marginTop = "0px";
    document.getElementById("div2").style.marginTop = "0px";

}
#main {
 background-color: grey;
 height: 1000px; 
 width: 100%;
 margin: 0;
 padding: 0;
 }

#div1 {
 background-color: red;
 height: 100px;
 width: 100%;
 margin-top: 0px;
   position: relative;

 }

#div2 {
 background-color: green;
 height: 100px;
 width: 100%;
 margin-top: 0px;
   position: relative;

 }
<div id="main">
  
  <div id="div1"> </div>
  
  <div id="div2"> </div>
  

  <button onclick="myFunction1()">Button 1</button>

  <button onclick="myFunction2()">Button 2</button>

</div>

只需向您的元素添加 CSS 过渡。您可以根据口味更改参数。我相信这是最干净、最有效的解决方案。

编辑:根据 OP 在评论中的要求,我展示了一个过渡函数示例,该示例使用极值模拟对过渡的轻微 "bounce" 影响。您可以快速创建自己的过渡函数并使用在线工具对其进行实时测试(例如:cubic-bezier.com) or the Chrome developer tools (you can click on a transition function for an element you are inspecting to edit the function in real time). Note that this functionality is currently not universally supported (see: Safari Bug 45761

Transitions on MDN

function myFunction1() {
    document.getElementById("div1").style.marginTop = "-110px";
    document.getElementById("div2").style.marginTop = "20px";
}

function myFunction2() {
    document.getElementById("div1").style.marginTop = "0px";
    document.getElementById("div2").style.marginTop = "0px";

}
#main {
 background-color: grey;
 height: 1000px; 
 width: 100%;
 margin: 0;
 padding: 0;
 }

/* *** THIS IS NEW *** */
#main div {
  -webkit-transition: margin 1s cubic-bezier(1,.7,.49,1.7);
          transition: margin 1s cubic-bezier(1,.7,.49,1.7);
}
/* *** END NEW *** */

#div1 {
 background-color: red;
 height: 100px;
 width: 100%;
 margin-top: 0px;
   position: relative;

 }

#div2 {
 background-color: green;
 height: 100px;
 width: 100%;
 margin-top: 0px;
   position: relative;

 }
<div id="main">
  
  <div id="div1"> </div>
  
  <div id="div2"> </div>
  

  <button onclick="myFunction1()">Button 1</button>

  <button onclick="myFunction2()">Button 2</button>

</div>