文本溢出的进一步优化

情景

最近项目中刚好遇到文本过长需要显示… 但是由于信息较为重要,又没有其他操作去查看文本内容,因此做了一个移入显示的,其实网上这种实现的方式很多,项目我用的是伪元素去实现的,因为要求不高,后面想着这个效果应该还能继续优化,因此有了这篇博客,各位看官兄弟可以点点小手,帮忙赞一波

先看效果

写的demo 大家不要太在意样式问题啦
在这里插入图片描述

思考

1.让文本溢出显示…很容易做到,基本上项目里面都会封装一个类,使用的时候添加类名即可,这里多嘴一句,给大家加深点印象,显示这样的效果必须满足这四个条件
* 须有容器宽度:width:value;
* 强制文本在一行内显示:white-space:nowrap;
*溢出内容隐藏:overflow:hidden;
*溢出文本显示“…”:text-overflow:ellipsis;
2.要做到让文本超出的时候才显示上面的提示,未超出的时候不显示,那么我怎么才能知道它是否超出了呢,想了好久未想出好的方案,然后一番。。。之后得到了灵感 ,在每次渲染这个文本的时候,多渲染一个副本,由于文本设置了overflow:hidden 如果超出去了,副本的宽度肯定要大于文本

因此
       *鼠标移入的时候,将事件对象和下标传递过来
       *通过事件对象拿到文本和副本的宽度进行比较
       *如果副本的宽度大于文本的宽度,那么显示出附文

	   *鼠标移入就不显示
	   (显示和隐藏大家很容会想到用V-show或者if,其实用在这里都是不合适的,v-show利用的是display none,因此宽度始终是0,注意用visibility)

上代码,可放在Vue项目直接运行


<template>
	<div id="home">
		<div class="div_box" v-for="(item,index) in textList" :key="index">
			<p class="p1" @mouseover="mouseover($event,index)" @mouseout="mouseout">{{item.longText}}</p>
			<p class="hide" :style="{'visibility':item.actived}">{{item.longText}}</p>
		</div>
	</div>
</template>
<script>
export default {
	name: 'Home',
	data() {
		return {
			textList: [
				{
					actived: 'hidden',
					longText: '这里是一条很长很长的文本很长很长'
				},
				{
					actived: 'hidden',
					longText: '这里是一条很长很长的文本很长很长'
				},
				{
					actived: 'hidden',
					longText: '这里是一条短文本'
				}
			]
		}
	},
	methods: {
		mouseover($event, index) {
			//获取当前dom对象的宽度和它兄弟元素的宽度进行比较
			let this_width = $event.target.offsetWidth
			let next_width = $event.target.nextSibling.offsetWidth
			console.log(next_width)
			if (next_width > this_width) {
				this.textList[index].actived = 'visible'
			}
		},
		mouseout() {
			// this.textList[index].actived = 'hidden'
			this.textList.forEach(i => {
				i.actived = 'hidden'
			})
		}
	},

	created() {},
	mounted() {}
}
</script>
<style lang="scss" scoped>
#home {
	width: 100%;
	height: 100%;
	padding: 300px 0;
	.div_box {
		width: 200px;
		border: 1px solid #000;
		margin: 0 auto;
		font-size: 16px;
		margin-bottom: 20px;
		position: relative;
		.p1 {
			// 强制文本在一行内显示
			white-space: nowrap;
			// 溢出内容隐藏
			overflow: hidden;
			// 溢出文本显示...
			text-overflow: ellipsis;
			color: blue;
		}
		.p2 {
			color: red;
		}
		.hide {
			white-space: nowrap;
			position: absolute;
			top: -28px;
			left: 50%;
			transform: translateX(-50%);
			background-color: rgba(0, 0, 0, 0.5);
			padding: 5px 5px;
			border-radius: 20px;
			color: #fff;
		}
	}
}
</style>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值