您说得对,奎尔使用Delta来描述其内容.要获得当前的增量,可以使用quill.getContents
,要设置新的增量,可以使用quill.setContents
.
要保留插入符号的位置,可以使用getSelection
和setSelection
.
然而,问题是text-change事件发生在DOM更新之后.目前还没有真正内置的,比如before-text-change
.这similar Issue有更多关于在text-change
事件期间修改内容的问题的详细信息.一种方法是将更新包装在queueMicrotask
中.
下面是一个结合了上面提到的方法的工作示例,它在文本更改上取代了<3
到❤️
.你可以扩展它来替换其他表情符号和链接,尽管它可能会像问题中所说的那样存在问题.
var quill = new Quill('#editor', {
theme: 'snow'
});
quill.on('text-change', update);
update(); //update for initial texts
function update(delta, oldContents, source) {
if (source === 'silent') return;
const newContents = quill.getContents()
.map((op) => {
if (typeof op.insert === 'string') {
op.insert = op.insert.replaceAll('<3', '❤️');
}
return op;
});
queueMicrotask(() => {
//getSelection be queued after DOM update to get copy-paste position updates
const selection = quill.getSelection();
quill.setContents(newContents, 'silent');
//don't set caret position if the editor wasn't focused before
if (selection)
quill.setSelection(selection.index, 0, 'silent');
});
}
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<div id="editor">
<p>Hello World!</p>
<p>Some initial <strong>bold <3 </strong> text <3 <3</p>
<p><br></p>
</div>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>