css+js实现:文本超出宽度时显示省略号并悬浮气泡框

背景

  • 技术栈:vue + antd-vue
  • 目的:文本不超出宽度时正常显示,文本超出宽度时显示省略号并悬浮气泡框
  • 实现方案:鼠标移入时判断子元素的宽度与父元素的宽度,对比得出是否需要显示悬浮气泡框

具体实现

// v-for循环
<div
	class="content-item"
	v-for="card in list"
	:key="card.tenantcode">
	<a-tooltip :visible="card.showNameTip" :title="card.tenantname">
		<div class="tenant-item-name">
			<span 
				@mouseover="(e) => overName(e, card)"
				@mouseleave="card.showNameTip = false">
				{
    
    {
    
    card.tenantname}}
			</span>
		</div>
	</a-tooltip>
</div>

<script>
// 比较span子元素与div父元素之间的宽度,超出宽度时手动控制气泡框显示
// 除此之外,在生成对应list时,需要对数组内的对象元素增加showNameTip: false
overName(e, card) {
    
    
	const parentWidth = e.currentTarget.parentNode.offsetWidth;
    const contentWidth = e.currentTarget.offsetWidth;
    if (contentWidth > parentWidth) card.showNameTip = true
},
</script>

<style>
.tenant-item-name {
    
    
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_44242707/article/details/129485831