Home > Enterprise >  Animate rect height on first load and on mouse hover/out
Animate rect height on first load and on mouse hover/out

Time:11-18

it's the first time I use Vue.js and I need to do a very simple animation on component first load.

This is my 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>

Now, I want that on the first load, the red rectangle height goes from 0% to 100% in 2sec and then it should behave like now so on mouse hover the height become 0, on mouse out 100%. To do that I create a isFirstLoad variable and I'm switch between the two new classes height-0 and height-100.

Here the code:

<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>

It works on first load but then, the rect height is always 0%. I suppose because I set height-0 always. How can I fix?

CodePudding user response:

Try like following snippet:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related