划词高亮
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a3df8f200d543c320e6f3f5afdf8d581.gif#pic_center)
数据结构
HighlightRange
class HighlightRange {
start: DomNode;
end: DomNode;
text: string;
id: string;
}
DomNode
export interface DomNode {
$node: Node;
offset: number;
}
选区高亮
获取Range对象
export const getDomRange = (): Range => {
const selection = window.getSelection();
if (selection.isCollapsed) {
console.debug('no text selected');
return null;
}
return selection.getRangeAt(0);
};
生成HighlightRange 对象
- Range对象 + id -> HighlightRange 对象
static fromSelection(idHook: Hook) {
const range = getDomRange();
if (!range) {
return null;
}
const start: DomNode = {
$node: range.startContainer,
offset: range.startOffset
};
const end: DomNode = {
$node: range