我有以下项目,该项目基于突出显示在hashtags
框中编写的contenteditable
。
问题在于代码不允许我创建换行符。
我需要能够创建新行,并且光标位置工作良好。
$(document).ready(function() {
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
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);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ((sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
function setCaretPosition(element, offset) {
var range = document.createRange();
var sel = window.getSelection();
var currentNode = null;
var previousNode = null;
for (var i = 0; i < element.childNodes.length; i++) {
previousNode = currentNode;
currentNode = element.childNodes[i];
while (currentNode.childNodes.length > 0) {
currentNode = currentNode.childNodes[0];
}
if (previousNode != null) {
offset -= previousNode.length;
}
if (offset <= currentNode.length) {
break;
}
}
if (currentNode != null) {
range.setStart(currentNode, offset);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
var textbox = $(".textbox");
$(document).on("input", textbox, function(event) {
var position = getCaretCharacterOffsetWithin(textbox.get(0));
var text = textbox.text();
text = text.replace(/(^|\s)(#[^\s]+)/ig, "$1<span style=\"color: blue;\">$2</span>");
textbox.html($.parseHTML(text));
setCaretPosition(textbox.get(0), position);
});
});
.textbox {
padding: 6px;
border: solid 1px #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="textbox" contenteditable="true"></div>