1.需求:需要實(shí)現(xiàn)文本單行顯示,超出時(shí),使用省略號(hào),劃過該文本時(shí)使用tooltip顯示全部文本。需要考慮數(shù)據(jù)是由接口動(dòng)態(tài)獲取,只有溢出文本鼠標(biāo)滑過時(shí)顯示全部文本,沒有溢出的則不需要。
2.實(shí)現(xiàn):
第一步:首先要判斷文本是否溢出
這里網(wǎng)上可以找到很多方法,我是用scrollWidth去拿到實(shí)際文本長(zhǎng)度,跟clientWidth文本可視寬度作比較。需要注意的是我遇到了一個(gè)問題,即
判斷文本溢出之前一定要使用單行文件溢出顯示省略號(hào)的css,并且要加在tooltip內(nèi)部要溢出隱藏的span上,不然scrollWidth和clientWidth會(huì)一直為0文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-810411.html
onMouseOver(event) {
const ev = event.target;
const evWeight = ev.scrollWidth;
const contentWidth = ev.clientWidth;
if (evWeight > contentWidth) {
this.isShowTooltip = false;
} else {
this.isShowTooltip = true;
}
},
<el-row v-for="(row, rowIndex) in djnumberOfRows" :key="rowIndex">
<el-col
v-for="(column, colIndex) in row.length"
:key="colIndex"
:span="
calculateSpan(row, rowIndex, djnumberOfRows.length, colIndex)
"
>
<template v-if="row[colIndex]">
<el-form-item class="radioClass" :label="row[colIndex].name">
<el-tooltip
:content="djForm ? djForm[row[colIndex].fieldskey] : ''"
:disabled="isShowTooltip"
placement="top"
>
<div
@mouseover="onMouseOver($event)"
style="
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
"
>
{{ djForm ? djForm[row[colIndex].fieldskey] : '' }} //之前我在這里包了一層span,是錯(cuò)誤的,會(huì)導(dǎo)致拿到的不準(zhǔn),有的是0,有的地方不是,因?yàn)閟pan有范圍。為什么會(huì)在這加一層span,用div,因?yàn)槭÷蕴?hào)
</div>
</el-tooltip>
</el-form-item>
</template>
</el-col>
</el-row>
補(bǔ)充:(未試)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-810411.html
methods: {
onMouseOver (str) { // 內(nèi)容超出,顯示文字提示內(nèi)容
const tag = this.$refs[str]
const parentWidth = tag.parentNode.offsetWidth // 獲取元素父級(jí)可視寬度
const contentWidth = tag.offsetWidth // 獲取元素可視寬度
this.isShowTooltip = contentWidth <= parentWidth
}
}
到了這里,關(guān)于vue、element-ui使用el-tooltip判斷文本是否溢出的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!