我在 HTML 中有这个内容可编辑的 div
<div contenteditable="true" id="TextOnlyPage"></div>
这是我的 jquery 代码
var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm");
$('#TextOnlyPage').keyup(function(e){
if(e.keyCode == 13){
e.preventDefault();
$('#TextOnlyPage').children().each(function() {
if ( $(this).is("div") ) {
$(this).contents().unwrap();
}});
$('#TextOnlyPage').append("<br/>");
}
$('#TextOnlyPage').children().contents().unwrap();
var $this = $(this);
var content = $this.html();
$this.html(content.replace(rxp, "<span class='highlight'>$1</span>"));});
问题是插入符位置,因为当它在 string.replace 方法中围绕数字应用 span 标签时,光标会转到内容可编辑 div
的开头。当我按下回车键时,它也无法转到下一行。
我知道我可以通过 range
和 selection
对象来处理它,但是找不到有用的资源来理解这些对象的工作原理。
请为我提供这个问题的解决方案,如果在 angularjs 中提供解决方案会更好,或者为我提供一个资源,让我可以通过工作示例理解范围和选择对象。
最佳答案
我遇到了和你刚才一样的问题,为了理解 range
和 selection
是如何工作的,我建议你看一下 MDN 文档 Selection和 Range
检测 contentEditable
div 变化的一种可靠方法是事件 input
。我在监听 keyUp
并阻止某些 keyCode
的默认行为时发现的一个问题是它们很多,很难涵盖所有用例。
我更喜欢做的是让正常的事件被处理,保存插入位置,获取文本值并替换需要突出显示的部分,然后将插入位置设置回来。
这是一个简单的例子
var contentEditable = document.querySelector('div[contenteditable]');
contentEditable.addEventListener('input', onInput);
var onInput = function(e) {
// this function will be called after the current call-stack
// is finished, at that time the user input will be inserted
// in the content editable
setTimeout(function() {
// save the caret position
var text = contentEditable.innerText;
// perform all your replacement on `text`
contentEditable.innerHTML = text;
// set the caret position back
}, 0);
}
我还编写了两个方便的方法 getCaretOffsetWithin
和 setCaretPositionWithin
来在您想要执行一些 DOM 操作时帮助操作插入符号,并在之后将插入符号重新定位到其初始值处理。
您可以在这个要点上查看它们 contenteditable-utils.js
关于javascript - 处理内容可编辑 div 中的插入符位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859542/