最近做一个资源共享的需求,要求将资源名称,共享目标人的工号一定要显示出来,也就是文本超长,显示省略点,但是如果使用css,文本超长省略号会在末尾显示,因此利用js截取来实现
复制代码
1
2
3
4
5//获取字体是为了计算文本所占用的宽度,必须传递一个dom节点,随便选择一个即可,因为系统的字体都是一样的 mounted(){ // 获取系统字体 this.getFontFamily(document.getElementById('side-content')) },
将获取的字体参数使用全局变量存储起来,供计算文本宽度当成参数使用
复制代码
1
2
3
4getFontFamily(elem) { this.computedStyles = window.getComputedStyle(elem)['font-family'] console.log(this.computedStyles,'当前系统所用字体') },
根据文本内容获取当前截取文字所用的屏幕宽度
复制代码
1
2
3
4
5
6
7
8// 获取当前文本所占用的宽度 getTextWidth(text, font) { const canvas = this.getTextWidth.canvas || (this.getTextWidth.canvas = document.createElement("canvas")) const context = canvas.getContext("2d") context.font = font const metrics = context.measureText(text) return metrics.width },
核心方法,判断文本,逐步截取,当文本宽度超出设定宽度时,截取的当前文字拼接上+'...'+字符串末尾截取 就是完整文本,但是我的工号长度是不一定的,因此利用前一段文本+后一段文本==定宽,这样当工号后面长一些的时候,前面就少截取一部分内容,当工号后面的内容过长,前部分文本就多截取一些
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16handleSubstring(arr){ let _this = this arr.forEach(item=>{ let str='' let newStr = item.targetPath.substring(item.targetPath.lastIndexOf("工号"),item.targetPath.length); for (let i = 0; i < item.targetPath.length; i++) { if(_this.getTextWidth(str,`normal 14px ${_this.computedStyles}`) + _this.getTextWidth(newStr,`normal 14px ${_this.computedStyles}`)>270){ _this.$set(item,'newtargetPath',str+'...'+newStr) break } else { str+=item.targetPath[i] } } }) console.log(arr,'处理之后的arr数据') },
最后看下成果图:
最后
以上就是疯狂春天最近收集整理的关于vue中实现当文本超长时,中间显示省略点,两端文字显示的全部内容,更多相关vue中实现当文本超长时内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复