CSS下拉框收缩动画 Vue组件

发布于:2022-12-28 ⋅ 阅读:(229) ⋅ 点赞:(0)

实现效果

在这里插入图片描述


思路

利用CSS的 scaleY() 方法,将div在垂直方向上缩放,实现缩放效果。

  • 收起状态: transform: scaleY(0);
  • 展开状态: transform: scaleY(1);
  • 缩放中心设置在顶部: transform-origin: center top;
  • 动画效果: transition: all ease-in-out .3s;

代码示例

1. 定义 ToolButton 组件

// ToolButton 组件
<template>
  <div class="tool-btn">
    <div class="btn" @click="handleBtnClick">
      <span><slot name="btn-name" /></span>
      <i :class="['el-icon-caret-bottom', expandVisible ? 'active':'']"></i>
    </div>
    <div :class="['expand-box', expandVisible ? 'active':'']">
      <slot name="content" />
    </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      expandVisible: false
    }
  },
  methods:{
    handleBtnClick(){
      this.expandVisible = !this.expandVisible
    }
  }
}
</script>

<style lang="scss">
.tool-btn{
  z-index: 99;
  position: absolute;
  top: 10vh;
  left: 26vw;
  font-size: 0.91vw;
  font-family: SimHei;
  color: #fff;
  .btn{
    display: flex;
    height: 2.4vw;
    width: 7vw;
    align-items: center;
    justify-content: center;
    background-color: rgba(9, 31, 120, 0.6);
    &:hover{
      cursor: pointer;
    }
    i{
      margin-left: 3px;
      transition: all ease-in-out .3s;
      transform:rotate(0deg);
      &.active{
        transform:rotate(-180deg);
      }
    }
  }
  .expand-box{
    position: relative;
    margin-top: 5px;
    background-color: rgba(9, 31, 120, 0.6);
    transition: all ease-in-out .3s; // 过渡动画
    width: 150px;
    transform-origin: center top; // 缩放中心设置在面板顶部
    transform: scaleY(0);  // 面板收起
    max-height: 0; // 收起时div不占高度
    &.active{
      transform: scaleY(1); // 面板展开
      max-height: 200px;  // heigth:auto 无法触发过渡
    }
  }
}
</style>

2. 调用组件

<template>
  <tool-button class="planning-tool">
    <template #btn-name>
      规划归集
    </template>
    <template #content>
      XXXXXX
    </template>
  </tool-button>
</template>

<script>
import ToolButton from '@/components/ToolButton'

export default {
  components:{
    ToolButton
  }
}
</script>

<style lang="scss">
.planning-tool{
  margin-left: calc(6vw + 20px);
}
</style>

网站公告

今日签到

点亮在社区的每一天
去签到