const checkWidths = (text) => {
const tempElement = document.createElement('div');
tempElement.style.visibility = 'hidden';
tempElement.style.position = 'fixed'; // 使用绝对定位
tempElement.style.whiteSpace = 'nowrap'; // 不换行
tempElement.style.fontSize = '16'; // 获取字体样式
tempElement.style.fontFamily = 'Noto Sans SC"'; // 获取字体族
tempElement.innerText = text; // 设置文本
document.body.appendChild(tempElement);
console.log(`单元格内容 "${text}" 的真实宽度是: ${tempElement.offsetWidth}px`);
document.body.removeChild(tempElement);
return text;
};
const calculateIndex = (text) => {
const elementWidth = 200;
let totalWidth = 0;
index.value = null;
// 创建一个临时的 span 元素用于计算字符宽度
const tempSpan = document.createElement('span');
tempSpan.style.visibility = 'hidden';
tempSpan.style.position = 'absolute';
tempSpan.style.whiteSpace = 'nowrap';
document.body.appendChild(tempSpan);
for (let i = 0; i < text.length; i++) {
tempSpan.innerText = text[i]; // 设置当前字符
totalWidth += tempSpan.offsetWidth; // 累加字符宽度
if (totalWidth >= elementWidth) {
index.value = i; // 返回当前字符的索引
return text.slice(0, index.value - 1) + "...";
break;
}
}
document.body.removeChild(tempSpan); // 移除临时元素
return text;
};