vue項目開發的過程中,如果需要文字溢出的dom元素鼠標懸浮時才顯示title文字的話,可以封裝一個自定義的指令。
方法一、
組件內代碼如下:
directives: {
title: {
inserted(el) {
const { clientWidth, scrollWidth, title } = el;
if (!title && scrollWidth > clientWidth) el.title = el.innerText;
}
}
},
使用:
<article v-title>修修的鐵拳修修的鐵拳修修的鐵拳修修的鐵拳修修的鐵拳</article>
方法二、
或者鼠標進入後dom後方法處理,方法如下:
titeEnter(e) {
const target = e.target;
const { clientWidth, scrollWidth, title } = target;
if (!title && scrollWidth > clientWidth) target.title = target.innerText;
},
使用:
<article @mouseenter="titleEnter">修修的鐵拳修修的鐵拳修修的鐵拳修修的鐵拳修修的鐵拳</article>