点击换行功能

1、简介

设置文字超过限制长度后换行,换行后通过点击向上按钮切换到上一行,点击向下按钮切换到下一行,如果上一行或下一行没有文字则不切换,样式部分自行优化

本项目最终效果是这样

2、demo代码 

<template>
  <div>
    <div class="text-container">
      <div v-for="(line, index) in lines" :key="index" :class="['text-line', { 'active': index === currentLineIndex }]">
        {{ line }}
      </div>
    </div>
    <button @click="prevLine">上一行</button>  
    <button @click="nextLine">下一行</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: '这是一段很长很长的文本,需要进行换行展示。在这里我们可以通过 Vue 将其分解成多行,并通过点击按钮来切换展示不同的行。',
      lines: [],
      currentLineIndex: 0,
      lineLength: 10 // 每行最大字符数
    }
  },
  mounted() {
    this.splitText(this.text);
  },
  methods: {
    splitText(text) {
      if (text.length > this.lineLength) {
        const count = Math.ceil(text.length / this.lineLength);
        for (let i = 0; i < count; i++) {
          const start = i * this.lineLength;
          const end = (i + 1) * this.lineLength;
          const lineText = text.substring(start, end);
          this.lines.push(lineText);
        }
      } else {
        this.lines.push(text);
      }
    },
    prevLine() {
      const newIndex = this.currentLineIndex - 1;
      if (newIndex >= 0 && this.lines[newIndex]) {
        this.currentLineIndex = newIndex;
      }
    },
    nextLine() {
      const newIndex = this.currentLineIndex + 1;
      if (newIndex < this.lines.length && this.lines[newIndex]) {
        this.currentLineIndex = newIndex;
      }
    }
  }
}
</script>

<style scoped>
.text-container {
  width: 200px;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.text-line {
  display: none;
}

.text-line.active {
  display: block;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值