vue3实现文本超出鼠标移入的时候文本滚动
判断文本长度是否大于容器长度
鼠标移入的时候判断,此处使用了tailwindcss,注意一下要设置文本不换行。
<divref="functionsItems"@mouseenter="enterFunctionsItem($event, index)"><img class="w-5 h-5" :src="getIcon(item.addition)" /><spanclass="whitespace-nowrap">{{ item.name }}</span>
判断函数
如果大于,则添加动画函数。
const functionsItems = ref([])function enterFunctionsItem(e, index: number) {let width1 = functionsItems.value[index].scrollWidthlet width2 = functionsItems.value[index].children[1].scrollWidth// 减去内间距后对比if (width1 - 8 < width2 || width1 - 8 === width2) {// 添加classfunctionsItems.value[index].classList.add('scrollable-text')}
}
样式
@keyframes scroll {0% {transform: translateX(0%);}100% {transform: translateX(-50%);}
}.scrollable-text:hover span {overflow: visible;white-space: nowrap;animation: scroll 3s linear infinite;
}