需求:循环出来的数据,根据文本长度来控制是否显示鼠标悬浮提示el-tooltip
实现:监听窗口宽度,宽度改变,获取标签元素,判断可视窗口宽度与元素宽度大小,改变渲染与否
HTML部分
<div class="right-p4" v-for="(item, index) in overallResultsData.radarChart" :key="index">
<el-tooltip class="item" effect="dark" :content="(index + 1) + '. ' + item.name + ':' +item.des" placement="bottom-start" v-if="ellipsisList.includes(index)">
<p class="ellipsis"><span class="right-p4-name-black">{{ (index + 1) + '. ' + item.name + ':' }}</span><span class="right-p4-name-gray">{{ item.des}}</span>
</p>
</el-tooltip>
<p class="ellipsis" v-else><span class="right-p4-name-black">{{ (index + 1) + '. ' + item.name + ':' }}</span><span class="right-p4-name-gray">{{ item.des}}</span></p>
</div>
JS部分
beforeDestroy () {
window.removeEventListener('resize', this.handleResize)
},
mounted () {
window.addEventListener('resize', this.handleResize)
},
methods: {
handleResize () {
this.ellipsisList = []
const boxes = document.getElementsByClassName('ellipsis')
for (let i = 0; i < boxes.length; i++) {
const box = boxes[i]
if (box.scrollWidth > box.offsetWidth) {
// 如果显示省略号,则使用 el-tooltip 显示完整内容
this.ellipsisList.push(i)
}
}
},
}