其他分享
首页 > 其他分享> > vue 段落文字溢出中间... 尾部添加文字 组建

vue 段落文字溢出中间... 尾部添加文字 组建

作者:互联网

直接上代码
在components中创建paragraph.vue文件

<template>
    <div class="paragraph" ref="text" :style="`line-height: ${lineHeight}px;`" ></div>
</template>
<script>
export default {
  layout: "empty",
  props: {
    text: {
        type: String,
        default:''
    },
    lineHeight: {
        type: Number,
        default:18
    },
    rows:{
        ype: Number,
        default:3
    },
    suffix:{
        type: String,
        default:''
    }
  },
  methods: {
    overflowhidden (textDom, rows, lineHeight,suffix){
	      var at = rows*parseInt(lineHeight);      //计算包含文本的div应该有的高度
	     var tempstr = this.text;                       //获取到所有文本
	      textDom.innerHTML = tempstr;                //将所有文本写入html中
	     var len = tempstr.length;
	     var i = 0;
	      if(textDom.offsetHeight <= at){             //如果所有文本在写入html后文本没有溢出,那不需要做溢出处理
             textDom.innerHTML= tempstr + `<span style="color: #F67052;font-weight: 600;">${suffix}</span>`;
	     }else {                                   //否则 一个一个字符添加写入 不断判断写入后是否溢出
			var temp = "";
	         textDom.innerHTML = temp +  `<span style="color: #F67052;font-weight: 600;">${suffix}</span>`;
	         while(textDom.offsetHeight <= at){
	             temp = tempstr.substring(0, i+1);
	             i++;
	             textDom.innerHTML = temp + `<span style="color: #F67052;font-weight: 600;">${suffix}</span>`;
	         }
	         var slen = temp.length;
	         tempstr = temp.substring(0, slen-1);
	         len = tempstr.length
	         textDom.innerHTML  = tempstr.substring(0, len-3-this.suffix.length) +"..." + `<span style="color: #F67052;font-weight: 600;">${suffix}</span>`;     //替换string后面三个字符 
	     }
	     
	  }
  },
  mounted(){
      this.overflowhidden(this.$refs.text,this.rows,this.lineHeight,this.suffix)  
  }

};
</script>
<style lang="less" scoped>
.paragraph {
    font-size: 18px;
    color: #2C2D31;
    font-weight: 600;
    cursor: pointer;
  }
</style>


引用

import Paragraph from "~/components/paragraph.vue";

...



 components: { Paragraph },


使用

<Paragraph
                :lineHeight="26"
                :text="item.title"
                :rows="2"
                :suffix="item.rebate"
              ></Paragraph>

js原生地址:
js处理文字移出…

标签:文字,...,vue,suffix,default,textDom,rows,tempstr,var
来源: https://blog.csdn.net/wangxinyang0118/article/details/115557602