Vue实现移入父div显示子div、彻底移出父和子div时才不显示子div

623 阅读1分钟

动画.gif

实现结果

移入父元素时:显示子元素
直接移入子元素:不显示子元素
子元素显示时可以在子元素上任意移动,子元素都不会消失

实现思路

  1. Vue中右一个data是show,初始为false,为true时显示子元素
  2. mouseenter事件:只有在鼠标指针穿过被选元素时,才会触发此事件
  3. mouseleave事件:只有在鼠标指针离开被选元素时,才会触发此事件
  4. 对于父元素,设置其mouseenter事件为:将show设置为true
  5. 对于父元素,设置其mouseleave事件为:将show设置为false

代码

<template>
  <div>
    <div
      class="father"
      @mouseenter="showTrue"
      @mouseleave="showFalse"
    >
      <div class="son" v-if="show">
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false,
    };
  },
  methods: {
    showTrue() {
      this.show = true;
    },
    showFalse() {
      this.show = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.father {
  width: 200px;
  height: 100px;
  position: relative;
  background-color: #bfa;
}

.son{
  width: 200px;
  height: 400px;
  position:absolute;
  top:100px;
  background-color: #bbb;
}

</style>