项目中需要实现这么个效果
简而言之:鼠标选中一部分文字之后,停留在此状态,并添加前后标志
网上搜了没有此场景的实现方法,只能自己写了;
<div class="d-inline" ng-mousedown="cutMouseDown()"
ng-mouseup="cutMouseUp($event)" ng-bind-html="cutedSample"></div>
class CutDemo {
constructor() {
this.cutedSample = ''; // 等待被裁剪的字段
this.selection = null; // 裁剪字段选中的section
this.isParsed = false; // 是否已解析预览
this.maxLenSample = 'bbb'; // 未被裁剪的原字段
}
cutMouseDown() {
if (this.isParsed) return;
this.cutedSample = this.maxLenSample; // 恢复成纯字符串, 等待被再次裁剪
}
cutMouseUp(event) {
if (this.isParsed) return;
this.selection = this.getSelectText(event.target);
}
getSelectText() {
const selection = window.getSelection();
if (selection.type === 'Range') {
//Caret和null不是选中状态
const start = Math.min(selection.anchorOffset, selection.focusOffset);
const end = Math.max(selection.anchorOffset, selection.focusOffset);
if (start === end) return null;
const first = this.maxLenSample;
const startHtml = first.substring(0, start);
const middleHtml = first.substring(start, end);
const endHtml = first.substring(end);
const prefix = '<div class="selection-tag"><div class="st-dot"></div><div class="st-line"></div></div>'; // 标记前缀
const suffix = '<div class="selection-tag"><div class="st-line"></div><div class="st-dot"></div></div>'; // 标记后缀
this.cutedSample = startHtml + '<span class="selection-text">' + prefix + middleHtml + suffix + '</span>' + endHtml;
return {
text: selection.toString(),
end,
start,
focusNode: selection.focusNode,
anchorNode: selection.anchorNode,
rangeCount: selection.rangeCount,
};
} else {
return null;
}
}
}
样式:
.selection-text {
background-color: fade(#4ad3a3, 20);
position: relative;
.selection-tag {
position: absolute;
display: inline-flex;
flex-direction: column;
align-items: center;
width: 0;
.st-dot {
width: 5px;
height: 5px;
border-radius: 5px;
background-color: #4ad3a3;
}
.st-line {
width: 1px;
height: 10px;
background-color: #4ad3a3;
}
}
}
以上代码如有需要,可根据自己项目中的框架进行替换~