ckeditor:如何在焦点上选择编辑器内的所有文本

ckeditor: How to select all text inside editor on focus?

本文关键字:编辑器 文本 选择 焦点 ckeditor      更新时间:2023-09-26

我使用ckeditor进行文本格式化,编辑器中有默认文本,我想在任何时候都显示选中的焦点。

我的代码

HTML:

<textarea id="FirstTextEditor" >Hello</textarea>
Javascript:

$(document).ready(function(){
    CKEDITOR.instances.FirstTextEditor.on('focus', function () {
        // What is code i want write to select all text on focus?
    });
});

您可以简单地实现您想要的:

CKEDITOR.instances.["your instance here"].on( 'focus', function () { this.execCommand( 'selectAll' ); });

如果你使用的是JQuery,它会是这样的:

$(document).ready(function(){
    $('textarea').focus(function(e){
        var that = this;
        setTimeout(
            function() {
                that.select()
            }, 0);
    });
});

JSFiddle - http://jsfiddle.net/s6Z82/5/

您现在唯一要弄清楚的是如何从ckeditor .instances. firsttextedititor .on回调中获得当前元素,然后您就完成了。

为什么setTimeout(.., 0) ?

Cause似乎在Chrome e.p preventdefault()不会阻止它放弃选择并将光标放到行尾