gpt4 book ai didi

javascript - 使用转义键取消内联 tinyMCE 编辑

转载 作者:行者123 更新时间:2023-11-30 16:26:18 24 4
gpt4 key购买 nike

我希望用户能够使用转义键以内联模式中止 tinyMCE 编辑器中的任何更改。这是 HTML:

<div id="tinymce">
<p>Foo Foo Foo</p>
</div>

和脚本:

tinymce.init({
selector: '#tinymce',
inline: true,
setup: function (editor) {
editor.on('keydown', ((e) => {
var tinyMceEditor = tinyMCE.get(e.target.id);

if (e.keyCode === 27) { // escape
// This will hide the editor but it won't come back when trying to re-edit
tinyMceEditor.hide();
}
}));
}
});

它也是一个 jsfiddle:http://jsfiddle.net/kfnyqufm/

点击 escape 会像我想要的那样关闭编辑器,但有两个问题:(1) 单击文本时编辑器不返回 (2) 任何编辑的文本都不会恢复为原始值

最佳答案

(1)点击文本编辑器不返回

发生这种情况是因为当按下 esc 时您完全隐藏了编辑器,并且不再显示它。你有(至少)两个选项来解决这个问题:

  1. #tinymce div 再次获得焦点时显示编辑器;或
  2. 当按下 esc 时触发 #tinymce 上的 blur() 方法(这将自动隐藏编辑器,它会来再次点击返回)

如果你选择第二个选项(我认为它会更简单),代码将是这样的(只有与退出按钮相关的部分):

if (e.keyCode === 27) { // escape
document.getElementById("tinymce").blur();
}

你也可以在this version of your JSFiddle上看到它.

(2) 任何编辑过的文本都不会恢复到原始值

这有点棘手(但仍然很简单),因为您需要跟踪旧值并在按下 esc 时恢复。这样做的逻辑是:

  • #tinymce div 获得焦点时:将内部 HTML 保存到 JavaScript 变量中(或在 localStoragesessionStorage 中)。
  • 当按下转义键时:将保存的值恢复为#tinymce的内部HTML。

存储旧值的代码是这样的:

// define a variable to store the old value
var old_value = "";

// save the old value when #tinymce gets focus
document.getElementById("tinymce").addEventListener("focus", function() {
old_value = document.getElementById("tinymce").innerHTML;
}, false);

然后您还需要在按下 esc 时恢复旧值:

if (e.keyCode === 27) { // escape
// blur the tinymce div and restore the old value
document.getElementById("tinymce").blur();
document.getElementById("tinymce").innerHTML = old_value;
}

您可以看到它在 this version of your JSFiddle 上完全正常工作.

关于javascript - 使用转义键取消内联 tinyMCE 编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com