从CKEDITOR的textarea警告选择

时间:2012-10-19 09:36:29

标签: javascript ckeditor selection

我正在尝试提醒我从CKEDITOR中的textarea中选择的选择。 当我跑步时,只有"No text is selected."出来。 我想看警报"The current selection is: "+ selection. 我想我需要在这里改变var textarea = document.getElementById('editor1'); 任何人都可以帮我解决这个问题吗?

设置:

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);
    }
   }

1 个答案:

答案 0 :(得分:1)

要获得选择,请使用以下代码:

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

然而,此方法仅返回文本(无HTML标记)。


要保存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将存储您的选择HTML。