DIV CSS 佈局教程網

詳解 Vue 2.0 transition 在嵌套元素上的過渡設定
編輯:關於JavaScript     

做 Vue Demo 時遇到一個問題:當過渡的目標元素裡還嵌套著子元素,transition 該怎麼寫?子元素能不能一起動?以下是我當時的嘗試與結論。

最初的程式碼

<div id='demo'>
  <button @click="show = !show">按鈕</button>
  <transition name='move'>
    <div class="v-d" v-show="show">
      <div class='in in_move'></div>
    </div>
  </transition>
</div>
.v-d {
  width: 50px;
  height: 50px;
  padding: 10px;
  transition: all 0.4s linear;
}
.v-d .in {
  width: 30px;
  height: 30px;
  background: #000;
  transition: all 0.4s linear;
}
.move-enter-active, .move-leave-active {
  transition: all 0.4s linear;
}
.move-enter, .move-leave-active {
  opacity: 0;
  transform: translateX(30px);
}
.move-enter, .move-leave-active .in {
  transform: rotate(45deg);
}
window.onload = function () {
  new Vue({
    el: '#demo',
    data: {
      show: false
    }
  });
};

問題:子元素的過渡沒生效

我原本希望子元素 .in 在過渡過程中旋轉:

.move-enter, .move-leave-active .in {
  transform: rotate(180deg);
}

結果這段樣式完全沒作用。一開始我以為 Vue 不支援這種嵌套寫法,但反覆嘗試後才發現真正的原因:transition 產生的類名不能與元素本身既有的類名相同。也就是說,.in 這個類名必須換掉,過渡才會生效。

修改後的版本

<transition name='move'>
  <div class="v-d">
    <div class='in in_move'></div>
  </div>
</transition>
.move-enter, .move-leave-active .in_move {
  transform: rotate(180deg);
}

改完執行就正常了,位移與旋轉同時呈現。

為什麼會這樣

問題出在選擇器的優先順序。.move-enter 與 .v-d .in 都是兩個類名組成的選擇器,權重完全相同,此時後者若出現在樣式表更後面,就會把過渡樣式蓋掉;更糟的情況是瀏覽器不同、載入順序不同,結果也跟著不同。改用一個只屬於過渡狀態的專用類名(如 in_move),就徹底排除了這層衝突。

順帶補充兩個 Vue 2 的過渡要點:進入階段是 .xxx-enter 搭配 .xxx-enter-active,離開階段則是 .xxx-leave-active 搭配 .xxx-leave-active;而 transform、opacity 這類屬性要寫在「起始狀態」的類別上,transition -duration 則寫在 -active 類別上,兩者職責不同,寫錯就不會動。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved