你真的知道什么状况下text-overflow:ellipsis才会生效吗?

text-overflow:ellipsis是咱们用来设置文本溢出的一个经常使用属性。css

可是究竟什么状况才会触发文本溢出,大部分人确定没有探究过。
我之前也没有注意,反正这样的css样式一把梭,溢出了就点点点dom

width: 100px;
overflow: hidden;
text-overflow: ellipsis;

原本是没啥问题的,直到测试给我提了一个bug:表格内的文字超长隐藏后鼠标hover没有悬浮提示测试

clipboard.png

我一个开始不信,我用的element-UI还会出问题?
不过看完源码之后果真翻车了this

const cellChild = event.target.querySelector('.cell');
if (hasClass(cellChild, 'el-tooltip') && cellChild.scrollWidth > cellChild.offsetWidth && this.$refs.tooltip) {
//执行悬浮窗显示操做
}

问题就出在了cellChild.scrollWidth > cellChild.offsetWidth
为了方便控制元素宽度,设置了box-sizing: border-box;
按照理解scrollWidth是内容的宽度,offsetWidth是容器的宽度。
也不会出问题,可是谁也没想到当scrollWidth===offsetWidth时,
text-overflow:ellipsis竟然生效了。
重现效果:
http://jsfiddle.net/f0dmkkh8/1/spa

我天真的觉得cellChild.scrollWidth >= cellChild.offsetWidth不就完事了。.net

知道我看了element-UI最新的代码才发现本身错了,原来scrollWidth超出offsetWidth并非text-overflow:ellipsis触发的条件。3d

const range = document.createRange();
      range.setStart(cellChild, 0);
      range.setEnd(cellChild, cellChild.childNodes.length);
      const rangeWidth = range.getBoundingClientRect().width;
      const padding = (parseInt(getStyle(cellChild, 'paddingLeft'), 10) || 0) +
        (parseInt(getStyle(cellChild, 'paddingRight'), 10) || 0);

使用range对象截取dom片断后获取到的DOMRect对象的width才是内容的真正宽度。(scrollWidth并非内容区域的真正宽度)code

也就是说当对象

//加padding是应为box-sizing:border-box;
rangeWidth + padding > cellChild.offsetWidth

成立时才是触发text-overflow:ellipsis真正的条件。blog

相关文章
相关标签/搜索