JS如何判断文字是否溢出(被ellipsis)?

如果想要文本超出宽度后用省略号省略,只需要加上以下的css就行了。

.ellipsis {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

3行css搞定,但是问题来了:如果我们想要当文本被省略的时候,也就是当文本超出指定的宽度后,鼠标悬浮在文本上面才展示popper,应该怎么实现呢?

CSS帮我们搞定了省略,但是JS并不知道文本什么时候被省略了,所以我们得通过JS来计算。接下来,我将介绍几种方法来实现JS计算省略。

createRange


我发现Element-plus表格组件已经实现了这个功能,所以就先来学习一下它的源码。

源码地址:https://github.com/element-plus/element-plus/blob/dev/packages/components/table/src/table-body/events-helper.ts

// 仅仅粘贴相关的
const cellChild = (event.target as HTMLElement).querySelector('.cell') 
const range = document.createRange()
range.setStart(cellChild, 0)
range.setEnd(cellChild, cellChild.childNodes.length)
let rangeWidth = range.getBoundingClientRect().width
let rangeHeight = range.getBoundingClientRect().height
/** detail: https://github.com/element-plus/element-plus/issues/10790
* What went wrong?
* UI > Browser > Zoom, In Blink/WebKit, getBoundingClientRect() sometimes returns inexact values, probably due to lost
precision during internal calculations. In the example above:
* - Expected: 188
* - Actual: 188.00000762939453
*/
const offsetWidth = rangeWidth - Math.floor(rangeWidth)
if (offsetWidth < 0.001) {
  rangeWidth = Math.floor(rangeWidth)
}
const offsetHeight = rangeHeight - Math.floor(rangeHeight)
if (offsetHeight < 0.001) {
  rangeHeight = Math.floor(rangeHeight)
}


const { top, left, right, bottom } = getPadding(cellChild) // 见下方
const horizontalPadding = left + right
const verticalPadding = top + bottom
if (
  rangeWidth + horizontalPadding > cellChild.offsetWidth ||
  rangeHeight + verticalPadding > cellChild.offsetHeight ||
  cellChild.scrollWidth > cellChild.offsetWidth
) {
  createTablePopper(
    parent?.refs.tableWrapper,
    cell,
    cell.innerText || cell.textContent,
    nextZIndex,
    tooltipOptions
  )
}

// 上面代码17行中的getPadding函数
const getPadding = (el: HTMLElement) => {
  const style = window.getComputedStyle(el, null)
  const paddingLeft = Number.parseInt(style.paddingLeft, 10) || 0
  const paddingRight = Number.parseInt(style.paddingRight, 10) || 0
  const paddingTop = Number.parseInt(style.paddingTop, 10) || 0
  const paddingBottom = Number.parseInt(style.paddingBottom, 10) || 0
  return {
    left: paddingLeft,
    right: paddingRight,
    top: paddingTop,
    bottom: paddingBottom,
  }
}

document.createRange() 是 JavaScript 中的一个方法,用于创建一个 Range 对象,表示文档中的一个范围。Range 对象通常用于选择文档中的一部分内容,然后对其进行操作。

它可以:

  1. 设置选中文本范围:可以使用 document.createRange() 方法创建一个 Range 对象,并使用 setStart() 和 setEnd() 方法设置选中文本的起始和结束位置。
  2. 插入新元素:可以使用 document.createRange() 方法创建一个 Range 对象,并使用 insertNode() 方法将新元素插入到文档中的指定位置。
  3. 获取特定元素的位置:可以使用 document.createRange() 方法创建一个 Range 对象,并使用 getBoundingClientRect() 方法获取元素在文档中的位置和大小信息。

这边element就是使用range对象的getBoundingClientRect获取到元素的宽高,同时因为得到的宽高值有很多位的小数,所以element-plus做了一个判断,如果小数值小于0.001就舍弃小数部分。


接下来,就让我们进行一下复刻吧。

文字的宽度 + 盒子的左右padding  > 盒子的offsetWidth 则存在省略号

<div class="ellipsis box">
  Lorem ipsum dolor sit amet consectetur adipisicing elit
</div>
<div id="result"></div>

<script>
  const box = document.querySelector(".box");

  const getPadding = (el) => {
    const style = window.getComputedStyle(el, null);
    const paddingLeft = Number.parseInt(style.paddingLeft, 10) || 0;
    const paddingRight = Number.parseInt(style.paddingRight, 10) || 0;
    const paddingTop = Number.parseInt(style.paddingTop, 10) || 0;
    const paddingBottom = Number.parseInt(style.paddingBottom, 10) || 0;
    return {
      pLeft: paddingLeft,
      pRight: paddingRight,
      pTop: paddingTop,
      pBottom: paddingBottom,
    };
  };

  box.addEventListener("animationiteration", function () {
    const event = new CustomEvent("resize");
    box.dispatchEvent(event);
  });

  const checkEllipsis = () => {
    const range = document.createRange();
    range.setStart(box, 0);
    range.setEnd(box, box.childNodes.length);
    window.getSelection().addRange(range);
    const rangeWidth = range.getBoundingClientRect().width; // 所有文字的宽度
    const rangeHeight = range.getBoundingClientRect().height; // 所有文字的高度
    console.log(rangeWidth, rangeHeight);
    const { pLeft, pRight, pTop, pBottom } = getPadding(box);
    console.log(pLeft, pRight, pTop, pBottom, "--");
    const horizontalPadding = pLeft + pRight;
    const verticalPadding = pTop + pBottom;
    if (
      rangeWidth + horizontalPadding > box.offsetWidth ||
      rangeHeight + verticalPadding > box.offsetHeight ||
      range.scrollWidth > box.offsetWidth
    ) {
      result.textContent = "计算结果:存在省略号";
    } else {
      result.textContent = "计算结果:容器宽度足够,没有省略号了";
    }
  };

  checkEllipsis();

  box.addEventListener("resize", checkEllipsis);
</script>

<style>
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .box {
    border: 1px solid gray;
    padding: 10px;
    width: 300px;
    resize: both;
    /**触发频率**/
    animation: resize 0.1s infinite paused forwards;
  }

  .box:active {
    animation-play-state: running;
  }

  @keyframes resize {
    to {
      opacity: 1;
    }
  }
</style>

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值