1.判断光标是否选中文本
// 获取选中文本
getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
//ie浏览器兼容
return document.selection.createRange().text;
}
return '';
},
2.获得富文本框中光标的位置
//我项目中这么写的
this.range = window.getSelection().getRangeAt(0);
//网上搜的兼容写法
function getCursortPosition(element) {
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
console.log(range);
}
}
return range;
}
//element为富文本挂载的dom元素,返回的range为光标对应的位置
**如果调用range的insertNode方法,可以在光标对应的位置插入想要的dom元素,但是这里要注意的是,insertNode方法会把你插入的dom元素,里面父子关系的节点元素循环成兄弟节点插入到光标位置。
//https://www.cnblogs.com/xzhwill19900525/p/8608996.html
3.项目编辑器主要插入实现:
insertMethod(clickEvent) {
if (window.getSelection().type == 'None') {
console.log('页面编辑器中没有光标的时候', window.getSelection().type);
return;
}if (this.clickArea <= 0) {
console.log('光标不在富文本中,不做处理');
return;
}if (document.querySelector('#insertBlock')) return;
//获取光标位置,存在range中
this.range = window.getSelection().getRangeAt(0);
if (this.getSelectedText().trim()) {
console.log('此时有选中文本,划选插入');
var cloneCotext = this.range.cloneContents().children;
var newArr = [];
var childrenNodes = [];
if (cloneCotext.length) {
for (var i in cloneCotext) {
newArr.push(cloneCotext[i]);
if (cloneCotext[i].childNodes?.length) {
console.log(cloneCotext[i].childNodes);
Object.assign(childrenNodes, cloneCotext[i].childNodes);
}
}
}
let re = newArr.some(item => {
return item.tagName == 'ACTION';
});
let rechild = childrenNodes.some(item => {
return item.tagName == 'ACTION';
});
if (re || rechild) {
this.$message.error('划选内容非法,请重新选择');
return false;
}
document.getElementById('editorContainer').focus();
//选中文本存在selectedText中
this.selectedText = this.getSelectedText().trim();
let domB = document.createElement('b');
domB.setAttribute('id', 'insertBlock');
domB.setAttribute('style', 'background:green;width:5px;height: 1.75em;display: inline-block;');
let domSpan = document.createElement('i');
domSpan.setAttribute('id', 'inertSelect');
domSpan.appendChild(this.range.extractContents());
this.range.insertNode(domB);
this.range.insertNode(domSpan);
insertContClick.style.zIndex = -1;
//显示划选选择框
this.setSelectStyle(clickEvent.clientX, clickEvent.clientY);
} else {
document.getElementById('editorContainer').focus();
console.log('没有选择文本,是点插入', this.range.startContainer);
let domB = document.createElement('b');
domB.setAttribute('id', 'insertBlock');
domB.setAttribute('style', 'background:green;width:5px;height: 1.75em;display: inline-block;');
this.range.insertNode(domB);
insertContSelect.style.zIndex = -1;
//显示点选择框
this.setClickStyle(clickEvent.clientX, clickEvent.clientY);
}
},
参考文献:
3.一步步教你实现富本文编辑器(第一部分)