简体   繁体   English

警报来自CKEDITOR中文本区域的选择

[英]Alerting the selection from a textarea in CKEDITOR

i am trying to alert the selection that i choose from the textarea in CKEDITOR. 我试图提醒我从CKEDITOR中的textarea选择的选择。 when i run, just "No text is selected." 当我运行时,只是"No text is selected." comes out. 出来。 i want to see the alert "The current selection is: "+ selection. 我想查看警报"The current selection is: "+ selection. i think i need to change here var textarea = document.getElementById('editor1'); 我想我需要在这里更改var textarea = document.getElementById('editor1'); could anyone help me with the problem?? 谁能帮助我解决这个问题?

setup: 设定:

function () 
{
    var selection = "";
    var textarea = document.getElementById('editor1');
    if ('selectionStart' in textarea)
    {
         // check whether some text is selected in the textarea
         if (textarea.selectionStart != textarea.selectionEnd)
         {
           selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
         }
    }
    else
    {
        // Internet Explorer before version 9
       // create a range from the current selection
       var textRange = document.selection.createRange();
        // check whether the selection is within the textarea
      var rangeParent = textRange.parentElement();
      if (rangeParent === textarea)
      {
          selection = textRange.text;
      }
    }
    if (selection == "")
    {
       alert("No text is selected.");
    }
    else
    {      
       alert("The current selection is: " + selection);
    }
   }

To obtain the selection use the following code: 要获得选择,请使用以下代码:

CKEDITOR.instances.youEditorInstance.getSelection().getSelectedText();

This method however returns text only (no HTML markup). 但是,此方法仅返回文本(没有HTML标记)。


To save HTML markup, you can try something like this: 要保存HTML标记,您可以尝试执行以下操作:

var range = CKEDITOR.instances.editor1.getSelection().getRanges()[ 0 ];
var rangeClone = range.clone();

range.collapse();
var el1 = range.getCommonAncestor( true, true );
range.splitElement( el1 );

rangeClone.collapse( true ); // to beginning
var el2 = rangeClone.getCommonAncestor( true, true );
rangeClone.splitElement( el2 );

var html = '';
var newRange = CKEDITOR.instances.editor1.getSelection().getRanges()[ 0 ];
var children = newRange.cloneContents().getChildren();

var element;
for( var i = 0 ; i < children.count() ; i++ ) {
    element = children.getItem( i );
    html += element.$.innerHTML ? element.getOuterHtml() : '';
}

html will store your selection HTML. html将存储您选择的HTML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM