css+js implementation: when the text exceeds the width, the ellipses are displayed and the bubble box is suspended

background

  • Technology stack: vue + antd-vue
  • Purpose: Display normally when the text does not exceed the width. Display ellipsis and float the bubble box when the text exceeds the width.
  • Implementation plan: When the mouse moves in, determine the width of the child element and the width of the parent element, and compare it to determine whether the floating bubble box needs to be displayed.

Implementation

// 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>

Guess you like

Origin blog.csdn.net/qq_44242707/article/details/129485831