我正在寻找一个 TinyMCE 插件或其他自定义解决方案,它将自动转换为 —。理想情况下,该解决方案不需要在每个 keyPress/keyUp 事件上处理整个 TinyMCE 内容,而是仅检查用户何时剪切、粘贴或键入 -。现在我正在使用类似下面的东西,当TinyMCE内容很大时,它有点慢:
tinyMCE.init({
//...
setup: function (ed) {
ed.onKeyUp.add(function(ed) {
//find and replace two dashes with emdash
//if there was a change, update tinymce/textarea contents
});
}
});
更一般地说,我对 TinyMCE 的快速文本处理解决方案感到好奇。我知道可能没有什么比我现在使用的方法更好的了,但我只是想知道你们中是否有人找到了更好的解决方案。谢谢!
最佳答案
在setup中创建自定义处理函数
您的方向是正确的,您不需要为此使用插件。
在最基本的级别上,只需在事件回调中执行 .replace()
即可:
tinyMCE.init({
//...
setup: function (editor) {
editor.onKeyUp.add(function (editor) {
var content = editor.getContent({ format: 'html'}); // Get content in HTML entity encoded format
// RegEx replacements
content = content.replace(/--/g, '—'); // Convert two dashes into —
// Set content of iframe editor with modified string
editor.setContent(content, { format: 'html' });
});
}
});
但是您还需要监听 onChange
事件,并且由于您要将两个字符替换为一个字符,因此上述方法将导致光标位置移动不同步。
这是更好的方法:
tinyMCE.init({
//...
setup: function (editor) {
var customProcess = function (editor) {
var lastSelection = editor.selection.getBookmark(2, true), // Store last selection for later restoration
content = editor.getContent({ format: 'html'}); // Get content in HTML entity encoded format
// RegEx replacements
content = content.replace(/--/g, '—'); // Convert two dashes into —
// Set content of iframe editor with modified string
editor.setContent(content, { format: 'html' });
// Restore selection
editor.selection.moveToBookmark(lastSelection);
};
// Listen for change event
editor.onChange.add(customProcess);
// Listen for key up event
editor.onKeyUp.add(customProcess);
}
});
See this JSFiddle for a working example .
编辑:
我现在发现您正在寻找 onKeyUp
事件的替代方案。 onChange
事件可能是您最好的选择。我不知道还有其他快速处理解决方案。
关于javascript - 在 TinyMCE 中自动将两个破折号转换为 —,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8032294/