TinyMCE 在调用 execCommand 时窃取焦点

问题描述

我的 HTML 页面上有一堆输入,还有一个被 TinyMCE 编辑器替换的 textarea。加载此页面的情况有多种,并且每次其中一个输入都必须获得焦点。但是当 TinyMCE 被初始化时,它只是偷走了焦点。我将问题缩小到 execCommand 调用,该调用在 TinyMCE 中设置默认字体大小。

这个问题可以在这个简化的代码中重现:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
        <script>
            tinymce.init({
                selector: 'textarea',setup: function(editor) {
                    editor.on('init',function() {
                        this.execCommand("fontSize",false,"14pt"); // <<---- This line causes the TinyMCE editor to steal the focus!
                    });
                }
            });
        </script>
    </head>

    <body>
        <input id="inp" />
        <textarea>Hello,World!</textarea>
        
        <script>
            document.getElementById("inp").focus();
        </script>
    </body>
</html>

我在 Firefox、Chrome 和 Edge 中对此进行了测试,并且在所有这些中都发生了相同的问题。知道如何防止这种情况吗?一旦 TinyMCE 完成初始化,我不想再次设置焦点,因为此时页面已滚动到错误的位置。

解决方法

我知道我说过一旦 TinyMCE 完成初始化我不想“再次”设置焦点,但我最终做了类似的事情。我没有将焦点设置在页面底部,而是将代码移到 tinymce.init 中,并调用了 $(document).scrollTop(0);。代码如下:

tinymce.init({
    selector: 'textarea',setup: function(editor) {
        editor.on('init',function() {
            this.execCommand("fontSize",false,"14pt"); // <<---- This line causes the TinyMCE editor to steal the focus!
                        
            // Scroll to the top of the page.
            $(document).scrollTop(0);
            // Now set the focus.
            document.getElementById("inp").focus();
        });
    }
});

我相信 TinyMCE 中存在一个错误,我希望它在未来的某个版本中得到修复。我也希望这个变通办法能帮助到后来的人。

,

当您发出更改字体大小的命令时,实际上并没有在 TinyMCE 编辑器中设置默认字体。您正在触发这些命令,但如果有任何内容要加载到编辑器中,则不会应用此字体信息。

要在 TinyMCE 中使用 CSS 设置默认字体信息,可以通过 content_csscontent_style 配置选项:

https://www.tiny.cloud/docs/configure/content-appearance/#content_style

https://www.tiny.cloud/docs/configure/content-appearance/#content_css

以下示例显示了两种方法之间的差异。

在这个例子中:https://fiddle.tiny.cloud/oAhaab

...发出设置默认字体系列和大小的命令,但它们不会应用到然后加载到编辑器中的内容。它们被解雇,但最终不会应用于加载到编辑器中的内容。

然而,在这个例子中:https://fiddle.tiny.cloud/nAhaab

...默认字体信息按预期通过 CSS 应用于加载的内容。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...