Skip to content

@utilslib/web/isTextOverflowing


检测元素中的文字是否超出指定行数


isTextOverflowing

函数签名

typescript
function isTextOverflowing(element: HTMLElement, maxLines: number = 1): boolean

描述

检测元素中的文字是否超出指定行数

参数

参数名类型可选默认值描述
elementHTMLElement--
maxLinesnumber1-

返回值

boolean

点击查看源码
js
/**
 * 检测元素中的文字是否超出指定行数
 * @param element - 要检测的元素
 * @param maxLines - 最大行数,默认为1
 * @returns 文字是否超出了指定行数
 */
export function isTextOverflowing(element, maxLines = 1) {
  if (!element) return false;
  // 克隆元素以测量实际内容
  const clone = element.cloneNode(true);
  // 重置克隆元素的样式,让它完全展开
  const cloneStyle = clone.style;
  const originalStyle = getComputedStyle(element);
  cloneStyle.position = "absolute";
  cloneStyle.visibility = "hidden";
  cloneStyle.top = "-9999px";
  cloneStyle.left = "-9999px";
  cloneStyle.width = originalStyle.width;
  cloneStyle.height = "auto";
  cloneStyle.maxHeight = "none";
  cloneStyle.overflow = "visible";
  cloneStyle.textOverflow = "clip";
  cloneStyle.whiteSpace =
    originalStyle.whiteSpace === "nowrap" ? "nowrap" : "normal";
  cloneStyle.webkitLineClamp = "unset";
  // 临时添加到DOM中测量
  document.body.appendChild(clone);
  // 获取完全展开后的高度
  const fullHeight = clone.scrollHeight;
  // 移除克隆元素
  clone.remove();
  // 获取原始元素的单行高度
  const style = getComputedStyle(element);
  const lineHeight =
    style.lineHeight === "normal"
      ? parseFloat(style.fontSize) * 1.2
      : parseFloat(style.lineHeight);
  // 计算允许的最大高度
  const maxHeight = lineHeight * maxLines;
  // 比较完全展开的高度和允许的最大高度
  return fullHeight > maxHeight;
}
ts
/**
 * 检测元素中的文字是否超出指定行数
 * @param element - 要检测的元素
 * @param maxLines - 最大行数,默认为1
 * @returns 文字是否超出了指定行数
 */
export function isTextOverflowing(
  element: HTMLElement,
  maxLines: number = 1,
): boolean {
  if (!element) return false;

  // 克隆元素以测量实际内容
  const clone = element.cloneNode(true) as HTMLElement;

  // 重置克隆元素的样式,让它完全展开
  const cloneStyle = clone.style;
  const originalStyle = getComputedStyle(element);

  cloneStyle.position = "absolute";
  cloneStyle.visibility = "hidden";
  cloneStyle.top = "-9999px";
  cloneStyle.left = "-9999px";
  cloneStyle.width = originalStyle.width;
  cloneStyle.height = "auto";
  cloneStyle.maxHeight = "none";
  cloneStyle.overflow = "visible";
  cloneStyle.textOverflow = "clip";
  cloneStyle.whiteSpace =
    originalStyle.whiteSpace === "nowrap" ? "nowrap" : "normal";
  cloneStyle.webkitLineClamp = "unset";

  // 临时添加到DOM中测量
  document.body.appendChild(clone);

  // 获取完全展开后的高度
  const fullHeight = clone.scrollHeight;

  // 移除克隆元素
  clone.remove();

  // 获取原始元素的单行高度
  const style = getComputedStyle(element);
  const lineHeight =
    style.lineHeight === "normal"
      ? parseFloat(style.fontSize) * 1.2
      : parseFloat(style.lineHeight);

  // 计算允许的最大高度
  const maxHeight = lineHeight * maxLines;

  // 比较完全展开的高度和允许的最大高度
  return fullHeight > maxHeight;
}

如有错误,请提交issue :::