美文网首页
vue中高度不定的收缩动画效果

vue中高度不定的收缩动画效果

作者: Bouc | 来源:发表于2020-04-21 21:49 被阅读0次

    实现过渡效果可以使用csstransition属性,但元素的height属性为auto时,transition就没有办法生效了。这时可以通过js获取元素的高度,动态设置样式。

    需求描述

    打开时默认隐藏内容,点击显示后平滑展开,显示内容

    具体代码如下:

    <template>
      <div class="card">
          <div class="content" ref="content">
             hello world
          </div>
          <div class="card-operation" @click="toggle">{{msg}}</div>
      </div>
    </template>
    
    
    <script>
    export default {
      data() {
        return {
          msg: '显示',
          height: 0
        }
      },
      mounted() {
        // offsetHeight 是一个只读属性,它返回该元素的像素高度
        this.height = this.$refs.content.offsetHeight
        // 高度设置为0隐藏元素
        this.$refs.content.style.height = 0
      },
      methods: {
        toggle() {
          this.msg = !!this.height ?  '显示'  :  '隐藏'
          this.$refs.content.style.height =  !!this.height  ? this.height + 'px' : 0
        }
      }
    }
    </script>
    
    <style>
     .card {
        border: 1px solid #ebebeb;
        border-radius: 3px;
        transition: 0.2s;
        margin-bottom: 24px;
      }
     .card:hover {
        box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
          0 2px 4px 0 rgba(232, 237, 250, 0.5);
      }
    
     /*关键 transition all 0.3s linear 0*/
     .content{
        overflow:hidden;
        transition: all 0.3s linear 0;
      }
    
    .card-operation {
        font-size: 14px;
        line-height: 44px;
        border-top: 1px solid #eaeefb;
        height: 44px;
        box-sizing: border-box;
        background-color: #fff;
        border-bottom-left-radius: 4px;
        border-bottom-right-radius: 4px;
        text-align: center;
        margin-top: -1px;
        color: #d3dce6;
        cursor: pointer;
        position: relative;
      }
    
     .card-operation:hover {
          background-color: #f9fafc;
          color: #409eff;
        }
    </style>
    

    相关文章

      网友评论

          本文标题:vue中高度不定的收缩动画效果

          本文链接:https://www.haomeiwen.com/subject/zylmihtx.html