demo:
判断文本是否过长,过长就显示“我过长啦”。
效果:
测试数据:
dataArr: [{
id: 'test0',
name: '哈哈哈哈哈',
isOverflow: false
},
{
id: 'test1',
name: '哈哈哈哈哈哈',
isOverflow: false
}
]
布局:
<div class="text-title">计算文本是否过长</div>
<div class="text-item" v-for="(item,index) in dataArr" :key="index">
<div class="item-name single-text" :id="item.id">
<span class="dot"></span>
<span class="text">{{item.name}}</span>
</div>
<div class="item-overflow" v-if="item.isOverflow">我超长啦</div>
</div>
计算是否过长(核心):
isTextOverflow(elId, padding) {
if (!elId) {
return
}
let isShow = false;
let cellChild = document.getElementById(elId);
if (cellChild) {
const range = document.createRange();
range.setStart(cellChild, 0);
range.setEnd(cellChild, cellChild.childNodes.length);
const rangeWidth = range.getBoundingClientRect().width;
if (rangeWidth + padding > cellChild.offsetWidth || cellChild.scrollWidth > cellChild.offsetWidth) {
isShow = true;
}
}
return isShow;
}
childNodes 属性返回节点的子节点集合
计算、更新数据:
setTimeout(() => {
for (var i = 0; i < this.dataArr.length; i++) {
let obj = this.dataArr[i];
if (obj) {
this.$set(obj, 'isOverflow', this.isTextOverflow(obj.id, 100));
}
}
}, 10);
对象obj在执行this.$set()更新前,必须持有isOverflow属性,否则在部分安卓手机,更新数据会无效。
部分css:
.text-item .item-name {
padding: 0px 50px;
width: 100px;
background-color: #E8E8E8;
}
.single-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
写完啦,(*^▽^*)