CKEDITOR我如何聚焦模糊元素

时间:2017-10-24 10:58:41

标签: php jquery ckeditor

您好我是CKEDTIOR的新手,我遇到了一些问题。当你点击ckeditor元素时我想要聚焦,当你点击它之外时我会聚焦。你能帮忙吗?

 var challengeEd = undefined;
$('#thechallenge').focus(function() {
    challengeEd = CKEDITOR.replace('thechallenge');
});
var solutionEd = undefined;
$('#thesolution').click(function() {
    solutionEd = CKEDITOR.replace('thesolution');
});     
var companyEd = undefined;
$('#thecompany').click(function() {
    editor = CKEDITOR.replace('thecompany');
});
var customeruseEd = undefined;
$('#thecustomeruse').click(function() {
    editor = CKEDITOR.replace('thecustomeruse');
});



$('body').click(function() {
    if (challengeEd != undefined)
        challengeEd.destroy();
    if (solutionEd != undefined)
        solutionEd.destroy();
    if (companyEd != undefined)
        companyEd.destroy();
    if (customeruseEd != undefined)
        customeruseEd.destroy();
})

2 个答案:

答案 0 :(得分:0)

良好的开端,但我发现blur部分存在问题。最好使用组件API,如果是CKEditor,则有blur event

  

当编辑器实例失去输入焦点时触发。

所以我会使用如下代码:

[ 'thesolution', 'thechallenge' ].forEach( function( selector ) {

  // Attach focus listener.
  document.querySelector( '#' + selector ).addEventListener( 'focus', function() {

    // Create editor.
    var editor = CKEDITOR.replace( selector );

    // When instance is ready - focus it.
    editor.on( 'instanceReady', function() {
      editor.focus();
    } );

    // When editor losses focus - destroy it.
    editor.on( 'blur', function() {
      editor.destroy();
    } );
  } );      
} );

代表HTML:

<textarea name="thechallenge" id="thechallenge" rows="10" cols="80">  
  <p>Foo Bar Baz</p>
</textarea>

<textarea name="thesolution" id="thesolution" rows="10" cols="80">  
  <p>Foo Bar Baz</p>
</textarea>

Live demo on codepen

因此,对于每个文本字段,有4个简单的步骤:

  1. 附加focus侦听器(本机或您可以使用jQuery)。
  2. 在焦点上初始化编辑器实例。
  3. 当编辑器准备就绪时 - 将其聚焦(初始化后它将不会被默认聚焦)。
  4. On blur destroy editor instance。

答案 1 :(得分:0)

这是另一种解决方案:

 for (instance in CKEDITOR.instances) {
    var editor = CKEDITOR.instances[instance];
    if (editor) {
        // Call showToolBarDiv() when editor get the focus
        editor.on('focus', function (event) {
            showToolBarDiv(event);
        });

        // Call hideToolBarDiv() when editor loses the focus
        editor.on('blur', function (event) {
            hideToolBarDiv(event);
        });

        //Whenever CKEditor get focus. We will show the toolbar span.
        function showToolBarDiv(event) {
            //'event.editor.id' returns the id of the spans used in ckeditr.
            $('#' + event.editor.id + '_top').show();
        }

        function hideToolBarDiv(event) {
            //'event.editor.id' returns the id of the spans used in ckeditr.
            $('#' + event.editor.id + '_top').hide()
        }
    }
}

});