//获取选区长度
function getSelectionRangeLen(htmlContent) {
// 创建临时容器
const tempContainer = document.createElement('div');
// 将HTML内容设置到临时容器中
tempContainer.innerHTML = htmlContent;
// 将临时容器插入到页面中
document.body.appendChild(tempContainer);
// 创建一个Range对象
const range = document.createRange();
// 将div元素的起始位置和结束位置作为范围的边界
range.selectNodeContents(tempContainer);
// 获取Selection对象
const selection = window.getSelection();
// 清除当前选区
selection.removeAllRanges();
// 将创建的Range对象添加到选区中
selection.addRange(range);
// 初始化选区长度
let selectionLength = 0;
// 遍历选区中的每个范围
for (let i = 0; i < selection.rangeCount; i++) {
// 获取当前范围
const range = selection.getRangeAt(i);
// 获取范围内的文本内容并累加长度
selectionLength += range.toString().length;
}
// 将临时容器从页面中移除
document.body.removeChild(tempContainer);
return selectionLength;
}