展开与收起

展开与收起

定位加单行文本溢出处理

<template>

  <div>

    <div class="firstBox">

      <div class="texts">

  ××××××××××××××××××××××××这里是文字×××××××××××××××××××××××××

      </div>

      <i @click="expand" class="expandBtn">{{ expend ? '展开' : '收起' }}</i>

    </div>

  </div>

</template>

<script>

export default {

  data() {

    return {

      expend: true // 是否展开,true为显示展开符号,实际为收起

    }

  },

  methods: {

    expand() {

      const texts = document.querySelector('.texts')

      if (this.expend) {

        texts.style.whiteSpace = 'normal'

      } else {

        texts.style.whiteSpace = 'nowrap'

      }

      this.expend = !this.expend

    }

  }

}

</script>

<style lang="less" scoped>

.firstBox {

  width: 60%;

  position: relative;

  font-size: 14px;

  text-align: left;

  border: 1px solid greenyellow;

  .texts {

    position: relative;

    overflow: hidden;

    white-space: nowrap;

    text-overflow: ellipsis;

    margin-right: 60px;

  }

  .expandBtn {

    position: absolute;

    bottom: 0;

    right: 10px;

  }

}

</style>

初始状态——收起
在这里插入图片描述
点击展开后
在这里插入图片描述

直接操作盒子高度

利用 max-height: 当盒子高度不超过最大高度时,盒子高度为实际高度; 当盒子高度超过最大高度时,盒子高度为最大高度

还是上面的例子,现在利用max-Height来控制展开与收起

  methods: {

    expand() {

      const texts = document.querySelector('.texts')

      if (this.expend) {

        texts.style.maxHeight = '16px'

      } else {

        texts.style.maxHeight = '1000px'

      }

      this.expend = !this.expend

    }

  }

  .texts {

    position: relative;

    // display: inline-block;

    overflow: hidden;

    max-height: 16px;

    margin-right: 60px;

  }

如果想要上略号效果,可以直接在文字后价格span,里面就放省略号,利用展开与收起控制它的显示与隐藏

inline-block;

overflow: hidden;

max-height: 16px;

margin-right: 60px;

}


如果想要上略号效果,可以直接在文字后价格span,里面就放省略号,利用展开与收起控制它的显示与隐藏

这两种都有一个缺点,因为"展开"、“收起" 用了绝对定位定位,为了避免文字与"展开"、“收起"有重合,给文字的盒子添加了margin/padding,导致文字与外面边框盒子有间隔,目前还没有想到好的方法(让文字与盒子之间没有间距,且"展开"、“收起"始终在文字后面,无遮挡)