【问题标题】:Animate rect height on first load and on mouse hover/out首次加载和鼠标悬停/移出时动画矩形高度
【发布时间】:2021-12-28 19:41:58
【问题描述】:

这是我第一次使用 Vue.js,我需要在组件首次加载时做一个非常简单的动画。

这是我的starting point

<template>
  <div id="app">
    <div class="rect" />
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
};
</script>

<style lang="scss">
#app {
  border: 2px solid black;
  width: 200px;
  height: 300px;
}
#app:hover {
  .rect {
    background-color: tomato;
    height: 0%;
  }
}
.rect {
  transition: all 1s ease;
  background-color: tomato;
  width: 100%;
  height: 100%;
}
</style>

现在,我希望在第一次加载时,红色矩形高度在 2 秒内从 0% 变为 100%,然后它的行为应该像现在一样,所以鼠标悬停高度变为 0,鼠标移出 100%。 为此,我创建了一个 isFirstLoad 变量,并在 height-0height-100 两个新类之间切换。

Here代码:

<template>
  <div id="app">
    <div class="rect" :class="{ 'height-100': isFirstLoad }" />
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
  data: function () {
    return {
      isFirstLoad: true,
    };
  },
  mounted() {
    setTimeout(() => {
      this.isFirstLoad = false;
    }, 2000);
  },
};
</script>

<style lang="scss">
#app {
  border: 2px solid black;
  width: 200px;
  height: 300px;

  .height-0 {
    height: 0%;
  }
  .height-100 {
    height: 100%;
  }
}
#app:hover {
  .rect {
    background-color: tomato;
    height: 0%;
  }
}
.rect {
  transition: all 1s ease;
  background-color: tomato;
  width: 100%;
  // height: 100%;
}
</style>

它在第一次加载时工作,但矩形高度始终为 0%。 我想是因为我总是设置height-0。我该如何解决?

【问题讨论】:

    标签: javascript css vue.js css-transitions


    【解决方案1】:

    尝试如下 sn-p:

    new Vue({
      el: '#app',
      data() {
        return {
          isFirstLoad: true,
        }
      },
      methods: {
        setHeight(toggle) {
          this.isFirstLoad = toggle;
        }
      },
      mounted() {
        setTimeout(() => {
          this.isFirstLoad = false;
        }, 2000);
      }
    })
    
    Vue.config.productionTip = false
    Vue.config.devtools = false
    #app {
      border: 2px solid black;
      width: 200px;
      height: 300px;
    }
    #app .height-0 {
      height: 0%;
    }
    #app .height-100 {
      height: 100%;
    }
    #app:hover .rect {
      background-color: tomato;
    }
    .rect {
      transition: all 1s ease;
      background-color: tomato;
      width: 100%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"
      @mouseover="setHeight(true)"
       @mouseleave="setHeight(false)">
        <div class="rect" :class="isFirstLoad ? 'height-100' : 'height-0'">
        </div>
    </div>

    【讨论】:

    • 感谢您的回答,但这不是我需要的。结果是不同的:矩形在第一次加载时应该有 100% 的高度,然后减少到 0%。而且我不喜欢用js来做mouseover/mouseleave,而只用css
    • 嘿伙计,现在试试,请我纠正答案,你用 vue 设置类所以你需要使用 js
    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2016-10-30
    • 2012-03-31
    相关资源
    最近更新 更多