# Transition 过渡

过渡可以为一个元素在不同状态之间切换的时候定义不同的过渡效果。

transition CSS属性是 transition-propertytransition-durationtransition-timing-functiontransition-delay

# 语法

/* Apply to 1 property */
/* property name | duration */
transition: margin-right 4s;

/* property name | duration | delay */
transition: margin-right 4s 1s;

/* property name | duration | timing function */
transition: margin-right 4s ease-in-out;

/* property name | duration | timing function | delay */
transition: margin-right 4s ease-in-out 1s;

/* Apply to 2 properties */
transition: margin-right 4s, color 1s;

/* Apply to all changed properties */
transition: all 0.5s ease-out;

transition属性可以被指定为一个或多个 CSS 属性的过渡效果,多个属性之间用逗号进行分隔。

# 检测过渡是否完成

使用 transitionend事件监听。

  <body>
    <style>
      .box {
        width: 200px;
        height: 200px;
        background-color: red;
        transition: background-color 1s linear 0s;
      }
      .box:hover {
        background-color: green;
      }
    </style>
    <div class="box"></div>
    <script>
      const el = document.querySelector('.box');
      el.addEventListener('transitionend', onTransitionEnd, true);
      el.addEventListener('webkitTransitionEnd', onTransitionEnd, true);
      function onTransitionEnd(event) {
        const { propertyName, elapsedTime } = event;
        console.log('过度结束', propertyName, elapsedTime);
      }
    </script>
  </body>
上次更新: 1/22/2025, 9:39:13 AM