CSS 单击按钮时的转换 - CodePen 示例

CSS transition when clicking on button - CodePen example

我有一个按钮可以在礼物盒上方添加图片。它是 2 帧 - 礼物盒,以及按下按钮时上方的图像。

图片刚好“弹出”框上方。我希望图像(在本例中为卡车)从礼物盒平稳过渡,并从卡车现在的 box/the 相同位置向上一点。我该怎么做?

Codepen 有一个简单的例子:

https://codepen.io/Arte_2/pen/dyOLYwN

      function myFunction() {
        document.getElementById("truck").innerHTML = `
    <img    src="https://i.pinimg.com/originals/e0/8b/14/e08b1415885d4d2ddd7fd3f75967da29.png"></img>`
        console.log(this.show)
      }

    </script>
  </head>
  <body>
    <div id ="truck"></div>
  <img class="box" src="https://img.pngio.com/png-file-svg-box-icon-vector-png-transparent-cartoon-free-box-icon-png-920_852.png" on-click="handleClick"></img>
    <button onclick="myFunction()">Click</button>
  </body>
</html>

CSS:

.header {
          display: flex;
          align-items: center;
        }

        .circle {
          height: 36px;
          width: 36px;
          border-radius: 50%;
          visibility: visible;
          background-color: var(green);

          display: flex;
          align-items: center;
          justify-content: center;
        }

        .icon {
          height: 26px;
          width: 26px;
          line-height: 0;
        }

        .header-text {
          display: flex;
          align-items: center;
          margin-left: 14px;
          height: 48px;
        }

        .container {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
        }

       img {
          height: 240px;
          width: 250px;
          flex-grow: 0;
        }

        .box {
          width: 350px;
          height: 350px;
        }

因为您没有编辑任何 CSS 属性。您只是使用 JavaScript.

创建一个新元素

您有两种选择:创建元素并使用 javascript 对其进行动画处理,或者更简单的方法是将元素置于页面中并对其高度进行动画处理,例如,使其出现。这是您的代码,其中将 class 切换到卡车 div 并根据其 classList:

出现或消失

<head>
  <link rel="styles.css" />
</head>

<body>
  <div id="truck"><img src="https://i.pinimg.com/originals/e0/8b/14/e08b1415885d4d2ddd7fd3f75967da29.png" class=""></img></div>
  <img class="box" src="https://img.pngio.com/png-file-svg-box-icon-vector-png-transparent-cartoon-free-box-icon-png-920_852.png" on-click="handleClick"></img>
  <button onclick="myFunction()">Click</button>

  <script>
    function myFunction() {
      document.getElementById("truck").classList.toggle("visible");
    }
  </script>
</body>

</html>


#truck {
  height: 0;
  transition: all 1s ease;
}
#truck.visible {
  height: 280px;
}