如何阻止编辑CKEDITOR textarea中的某些部分内容? [英] How to block editing on certain part of content in CKEDITOR textarea?

查看:259
本文介绍了如何阻止编辑CKEDITOR textarea中的某些部分内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的CKEDITOR表单预填充了与用户输入的文本一起提交的隐藏表。这工作正常,但有时用户按下backspace太多次,并删除隐藏的表。



有没有办法阻止编辑这个隐藏的表里面ckeditor textarea?因此,当用户按下backspace时,隐藏的表不受影响并保留。



CKEDITOR实例就绪后,此源(下面)放在CkEditor Textarea setData()属性),并且用户仅看到返回的< p>< / p> 值。在这种情况下,它的< p>我真的认为我可以这样做!< / p> 。它的描述他的个人资料,他可以保留和编辑它。其余的是隐藏的,只有在提交表单时才能在电子邮件中看到。其奇怪的是,< p>< / p> 在顶部,但如果用户按Backspace几次表格被删除,因此没有提交。

 < span id =messageTemplate1class =message> 

< p>我真的认为我可以做到!< / p>

< table class =hidestyle =font-size:12px;>
< tbody>
< tr class =hide>
< td>
由< strong>< a href =http://www.globalcastingcenter.com/talent/jack-bolton> Matt Faro发送的应用程序< / a>< / strong> for Audition:< a href =http://www.globalcastingcenter.com:80/CustomContentRetrieve.aspx?ID=4185493>需要演员< / a>
< / td>
< / tr>
< tr class =hide>
< td>
直接回复申请人:mantas@mantas.co或访问完整的个人资料:http://www.globalcastingcenter.com/talent/jack-bolton
< / td>
< / tr>
< / tbody>
< / table>
< table class =hidestyle =font-size:12px;>
< tbody>
< tr class =hide>
< td>< strong>简要资料摘要:< / strong>< / td>
< / tr>
< / tbody>
< / table>
< table class =hidestyle =font-size:12px;>
< tr class =hide>
< td>
< a href =http://www.globalcastingcenter.com/talent/jack-bolton>< img alt =src =http://globalcastingcenter.com/talent_images/4164035_258551_foto。 png?Action = thumbnail& amp; Width = 144& amp; amp; amp; height = 215/>< / a>
< / td>
< / tr>
< / tbody>
< / table>
< table style =font-size:12px; class =hide>
< tbody>
< tr class =hide>
< td>< strong>区域:< / strong>< / td>
< td>演员,额外< / td>
< / tr>
< tr class =hide>
< td>< strong>国家/地区:< / strong>< / td>
< td> WORLDWIDE,任何< / td>
< / tr>
< tr class =hide>
< td>< strong>年龄:< / strong>< / td>
< td> 26< / td>
< / tr>
< / tbody>
< / table>
< / span>

现在当我加载你的插件时,我的CKeditor框消失,请在测试页面上按应用 href =http://gcc-july.themantas.co.uk/auditions/actors-needed =nofollow> http://gcc-july.themantas.co.uk/auditions/actors-needed a>请首先登录,以便能够访问消息框登录名:tiknius@gmail.com pssw:test



我的配置文件:

  CKEDITOR.editorConfig = function(config)
{
config.toolbar ='MyToolbar';

config.toolbar_MyToolbar =
[

{name:'clipboard',items:['Undo','Redo']},
{名称:'styles',items:['FontSize']},
{name:'basicstyles',items:['Bold','Italic']},
{name:'paragraph' items:['Outdent','Indent']},

];

config.removePlugins ='contextmenu';
config.forcePasteAsPlainText = true;
config.pasteFromWordRemoveFontStyles = true;
config.pasteFromWordRemoveStyles = true;
config.extraPlugins ='cwjdsjcsconfineselection';
config.startupShowBorders = false;
config.disableObjectResizing = true;

};

这是禁用插件时框的外观: http://screencast.com/t/Kc2bIOU8md2



我使用您建议的HTML结构。

解决方案

我不得不玩弄一点,让它工作。



我包含了一个更新的内容块版本,并且插件代码块。






这是您更新的内容块。它包装在< span> 标签中时无效,因此将其包装在表格中。



您可能不喜欢边框和调整数据单元格周围出现的轮廓,如果是这样,请将以下设置添加到您的配置中:

config.startupShowBorders = false; / code>

config.disableObjectResizing = true;





需要在开始内容之前有空的< td> ,它阻止用户使用Ctrl A允许他们删除隐藏的表格。



我删除了< p>



< td> 隐藏表有一个& nbsp; 字符,它防止用户使用Ctrl A选择允许他们删除隐藏表的所有内容。如果您删除光标右侧的所有内容,则会导致光标丢失,但您可以点击内容重新开始编辑。



contenteditable =false属性由CkEditor使用,是必需的,但它不会执行整个作业。你可以尝试新的HTML而不激活插件,看看它本身有什么效果。



插件代码中有关于类和ID我使用了。

 <! -  Begin Wrapper Table that Replaces< span&元素 - > 
< table id =messageTemplate1class =message cwjdsjcs_editable>
< tbody>
< tr>
< td class =cwjdsjcs_not_editablecontenteditable =false>
< / td>
< td id =cwjdsjcs_editable_id>
我真的认为我可以做到这一点!
< / td>
< / tr>

< tr class =cwjdsjcs_not_editablecontenteditable =false>
< td colspan =2>
& nbsp;

<! - 开始原始内容 - >
< table class =hidestyle =font-size:12px; display:none;>
< tr class =hide>
< td>
由< strong>< a href =http://www.globalcastingcenter.com/talent/jack-bolton> Matt Faro发送的应用程序< / a>< / strong> for Audition:< a href =http://www.globalcastingcenter.com:80/CustomContentRetrieve.aspx?ID=4185493>需要演员< / a>
< / td>
< / tr>
< tr class =hide>
< td>
直接回复申请人:mantas@mantas.co或访问完整的个人资料:http://www.globalcastingcenter.com/talent/jack-bolton
< / td>
< / tr>
< / tbody>
< / table>
< table class =hidestyle =font-size:12px; display:none;>
< tbody>
< tr class =hide>
< td>< strong>简要资料摘要:< / strong>< / td>
< / tr>
< / tbody>
< / table>
< table class =hidestyle =font-size:12px; display:none;>
< tbody>
< tr class =hide>
< td>
< a href =http://www.globalcastingcenter.com/talent/jack-bolton>< img alt =src =http://globalcastingcenter.com/talent_images/4164035_258551_foto。 png?Action = thumbnail& amp; Width = 144& amp; amp; amp; height = 215/>< / a>
< / td>
< / tr>
< / tbody>
< / table>
< table style =font-size:12px; display:none; class =hide>
< tbody>
< tr class =hide>
< td>< strong>区域:< / strong>< / td>
< td>演员,额外< / td>
< / tr>
< tr class =hide>
< td>< strong>国家/地区:< / strong>< / td>
< td> WORLDWIDE,任何< / td>
< / tr>
< tr class =hide>
< td>< strong>年龄:< / strong>< / td>
< td> 26< / td>
< / tr>
< / tbody>
< / table>
<! - 结束原始内容 - >

< / td>
< / tr>
< / tbody>
< / table>
<! - 替换的结束Wrapper表< span>元素 - >






这是插件代码,它被称为cwjdsjcsconfineselection



要添加插件:

在plugins目录中创建一个名为cwjdsjcsconfineselection的文件夹: ckeditor / plugins /

在该目录中创建一个名为plugins.js的文件,并将下面的代码粘贴到该文件中。 我的错误:文件名为plugin.js,而不是插件.js。



如果您已经有额外的插件,请将cwjdsjcsconfineselection添加到extraPlugins配置设置,否则将此设置添加到您的配置中:

config.extraPlugins ='cwjdsjcsconfineselection'; p>

插件应该在下次加载编辑器时工作。



对于我的情况,当用户在不可编辑区域中单击以解释为什么光标被移动回到先前的选择。

  / * 
防止编辑的外挂程式的元素与不可编辑类以及具有可编辑类的块外的元素。
* /

// * **************************注意****** *********************注意****************************
/ *
lastSelectedElement变量用于存储所选的最后一个元素。

此插件使用elementspath插件,显示相对于编辑区域中当前选择的DOM树中的所有元素。

当选择改变时,elementsPathUpdate被触发,
我们在这个键上循环遍历树中的元素,检查分配给每个元素的类。

三个结果是可能的。

1)找到不可编辑的类:
循环停止,当前操作被取消,光标移动到上一个选择。
selectionChange钩子被触发以在整个实例中设置被还原的选择。

2)在循环期间找到可编辑类,in_editable_area标志设置为true。

3)找不到可编辑或不可编辑的类(用户在您的主容器外部点击)。
in_editable_area标志保持设置为false。

如果in_editable_area标志为false,则当前操作被取消,光标将移动到上一个位置。
selectionChange钩子被触发以在整个实例中设置被还原的选择。

如果in_editable_area标志为真,
lastSelectedElement更新为当前选定的元素,插件返回true。

---------------
如果不希望元素路径显示在编辑器窗口的底部,
你可以隐藏它与CSS而不是禁用elementspath插件。

元素路径插件创建并保持活动状态,因为我们正在改变插件中的路径。
#cke_path_content
{
visibility:hidden!important;
}

---------------
插件键所在的CSS类和ID。使用默认值或更新变量来使用您的首选类和ID:

var starting_element_id =始终在实例中发生的已知可编辑元素的ID。
不要使用像< table>,< tr>,< br />不包含HTML文本。
默认值= cwjdsjcs_editable_id

var editable_class =可编辑容器的类。
应该应用于包含可编辑元素的所有顶级元素。
默认= cwjdsjcs_editable

var non_editable_class =可编辑容器中不可编辑元素的类
适用于所有子元素都不可编辑的元素。
默认= cwjdsjcs_not_editable

* /

// * ********************** ****结束注***************************结束注************* *************


//使用编辑器注册插件。
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.plugins.html
CKEDITOR.plugins.add('cwjdsjcsconfineselection',
{
要求: ['elementpath'],

//插件初始化逻辑在这个方法里面
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.pluginDefinition.html #init
init:function(editor)
{
editor.on('instanceReady',function(instance_ready_data)
{
//创建将保存最后允许选择(用于当不可编辑的选择时使用)
var lastSelectedElement;
editor.cwjdsjcs_just_updated = false;

//本节通过选择一个已知的可编辑元素
// ***输入应该具有初始焦点的元素的ID ***重要***重要***
var starting_element_id =cwjdsjcs_editable_id;

var resInitialRange = new CKEDITOR.dom.range(editor.document);

resInitialRange.selectNodeContents(editor.document.getById(starting_element_id));
resInitialRange.collapse();

var selectionObject = new CKEDITOR.dom.selection(editor.document);

editor.document.focus();
selectionObject.selectRanges([resInitialRange]);

var sel = editor.getSelection();
var firstElement = sel.getStartElement();
var currentPath = new CKEDITOR.dom.elementPath(firstElement);

//设置已知可编辑元素的路径,激活selectionChange钩子以更新整个实例的选择。
editor ._。selectionPreviousPath = currentPath;
editor.fire('selectionChange',{selection:sel,path:currentPath,element:firstElement});
}); // *** END - editor.on('instanceReady',function(e)


//当用户选择一个新元素时,检查它们是否可以编辑它,
//如果不将光标移回到最后一个已知的可编辑选择
editor.on('elementsPathUpdate',function(resPath)
{
// selectionChangehook在这个代码块的末尾,elementsPathUpdate钩子触发
//不需要检查,因为我们只是更新了选择,所以旁路处理
if(editor.cwjdsjcs_just_updated = = true)
{
editor.cwjdsjcs_just_updated = false;
return true;
}

var elementsList = editor ._。elementsPath.list;
var in_editable_area = false;
var non_editable_class =cwjdsjcs_not_editable;
var editable_class =cwjdsjcs_editable;

for(var w = 0; w< elementList.length ; w ++){
var currentElement = elementsList [w];

//有时候选择非内容元素,捕获它们并将选择返回到可编辑区域。
if(w == 0)
{
//可以更改为切换。
if(currentElement.getName()==tbody)
{
in_editable_area = false;
break;
}

if(currentElement.getName()==tr)
{
in_editable_area = false;
break;
}
}

//如果选择在不可编辑的元素内,则从循环和复位选择中断。
if(currentElement.hasClass(non_editable_class))
{
in_editable_area = false;
break;
}

if(currentElement.hasClass(editable_class)){
in_editable_area = true;
}
console.log(currentElement);
console.log(currentElement.getName());
}

//如果选择在可编辑元素内,退出插件,否则重置选择。
if(in_editable_area){
lastSelectedElement = elementsList [0];
return true;
}

var resRange = new CKEDITOR.dom.range(editor.document);

resRange.selectNodeContents(lastSelectedElement);
resRange.collapse();
editor.getSelection()。selectRanges([resRange]);
resRange.endContainer。$。scrollIntoView();

//打开对话框窗口:
//它告诉用户他们选择了一个不可编辑的区域,并且光标已经返回到上一个选择
// currentEditorName = editor.name;
// openResDefaultDialog(currentEditorName);

try
{
var sel = editor.getSelection();
var firstElement = sel.getStartElement();
var currentPath = new CKEDITOR.dom.elementPath(firstElement);
editor.cwjdsjcs_just_updated = true;

editor ._。selectionPreviousPath = currentPath;
editor.fire('selectionChange',{selection:sel,path:currentPath,element:firstElement});

}
catch(e)
{}
});
} // *** END - init:function(editor)
}); // ************************************************ ************************************* END - CKEDITOR.plugins.add

要测试插件已加载,请在实例就绪触发器之后添加警报:

  editor.on('instanceReady',function(instance_ready_data)
{
alert(instanceReady);

要测试选择更改时是否触发插件,请在elementsPathUpdate触发器后添加警报:

  editor.on('elementsPathUpdate',function(resPath)
{
alert(elementsPathUpdate);


I have my CKEDITOR form prepopulated with hidden table which is being submitted together with user inputed text. This works fine, but sometimes user presses backspace too many times and deletes the hidden table.

Is there a way to block editing on this hidden table inside ckeditor textarea? So when user presses backspace the hidden table isn't affected and stays in.

As soon as CKEDITOR instance is ready this source (bellow) is put inside CkEditor Textarea (using setData() attribute) and User only sees the returned <p></p> value. In this case its <p>I really think I can do this!</p>. Its a description of his profile and he can keep it and edit it. The rest is hidden and only visible in e-mail when form is submitted. Its strange that <p></p> is on top but if user presses Backspace couple times the table gets deleted and therefor not submitted.

    <span id="messageTemplate1" class="message">

<p>I really think I can do this!</p>

<table class="hide" style="font-size: 12px;">
    <tbody>
        <tr class="hide">
            <td>
            Application sent by <strong><a href="http://www.globalcastingcenter.com/talent/jack-bolton">Matt Faro</a></strong> for Audition: <a href="http://www.globalcastingcenter.com:80/CustomContentRetrieve.aspx?ID=4185493">Actors Needed</a>
            </td>
        </tr>
        <tr class="hide">
            <td>
            Reply to applicant directly: mantas@mantas.co or visit full profile: http://www.globalcastingcenter.com/talent/jack-bolton
            </td>
        </tr>
    </tbody>
</table>
<table class="hide" style="font-size: 12px;">
    <tbody>
        <tr class="hide">
            <td><strong>Short Profile Summary:</strong></td>
        </tr>
    </tbody>
</table>
<table class="hide" style="font-size: 12px;">
    <tbody>
        <tr class="hide">
            <td>
            <a href="http://www.globalcastingcenter.com/talent/jack-bolton"><img alt="" src="http://globalcastingcenter.com/talent_images/4164035_258551_foto.png?Action=thumbnail&amp;Width=144&amp;Height=215" /></a>
            </td>
        </tr>
    </tbody>
</table>
<table style="font-size: 12px;" class="hide">
    <tbody>
        <tr class="hide">
            <td><strong>Areas:</strong></td>
            <td>Actor,Extra</td>
        </tr>
        <tr class="hide">
            <td><strong>Country:</strong></td>
            <td>WORLDWIDE,Any</td>
        </tr>
        <tr class="hide">
            <td><strong>Age:</strong></td>
            <td>26</td>
        </tr>
    </tbody>
</table>
</span>

Now when I load your plugin my CKeditor box disapears, please press "Apply" on testing page http://gcc-july.themantas.co.uk/auditions/actors-needed please login first to be able to access the message box Login name: tiknius@gmail.com pssw: test

My config file:

CKEDITOR.editorConfig = function( config )
{
    config.toolbar = 'MyToolbar';

    config.toolbar_MyToolbar =
    [

        { name: 'clipboard', items : [ 'Undo','Redo' ] },           
        { name: 'styles', items : ['FontSize' ] },
        { name: 'basicstyles', items : [ 'Bold','Italic'] },
        { name: 'paragraph', items : ['Outdent','Indent' ] },

    ];

    config.removePlugins = 'contextmenu';
    config.forcePasteAsPlainText = true;   
    config.pasteFromWordRemoveFontStyles = true;
    config.pasteFromWordRemoveStyles = true;
    config.extraPlugins = 'cwjdsjcsconfineselection';
    config.startupShowBorders = false;
    config.disableObjectResizing = true;

};

This is how the box looks when I disable your plugin: http://screencast.com/t/Kc2bIOU8md2

I use your suggested HTML structure.

解决方案

I had to play around with it a bit to get it to work. I added lots of documentation to the plugin code, if you have any questions after reading it through let me know.

I'm including an updated version of your content block and the plugin code block.


Here is your updated content block. It wasn't working when wrapped in the <span> tag, so I wrapped it in a table.

You may not like the border and resizing outlines that appear around the data cell, if that's the case, add these settings to your configuration:
config.startupShowBorders = false;
config.disableObjectResizing = true;

Some notes:
The empty <td> before your starting content is needed, it prevents the user from using "Ctrl A" to select everything which would allow them to delete the hidden table.

I removed the <p> tag from the starting content as it acted funky in this structure.

The <td> that holds the hidden tables has a &nbsp; character, it prevents the user from using "Ctrl A" to select everything which would allow them to delete the hidden table. It causes the cursor to get lost if you delete everything to the right of the cursor, but you can click on the content to begin editing again.

The contenteditable="false" attribute is used by CkEditor and is needed, but it doesn't do the whole job. You can try out the new HTML without activating the plugin to see what effect it has by itself.

There are notes in the plugin code about the classes and ID I used.

<!-- Begin Wrapper Table that Replaces <span> element -->
<table id="messageTemplate1" class="message cwjdsjcs_editable">
    <tbody>
        <tr>
            <td class="cwjdsjcs_not_editable" contenteditable="false">
            </td>
            <td id="cwjdsjcs_editable_id">
                I really think I can do this!
            </td>
        </tr>

        <tr class="cwjdsjcs_not_editable" contenteditable="false">
            <td colspan="2">
                &nbsp;

                <!-- Begin Original Content -->
                <table class="hide" style="font-size: 12px; display:none;">
                    <tbody>
                        <tr class="hide">
                            <td>
                            Application sent by <strong><a href="http://www.globalcastingcenter.com/talent/jack-bolton">Matt Faro</a></strong> for Audition: <a href="http://www.globalcastingcenter.com:80/CustomContentRetrieve.aspx?ID=4185493">Actors Needed</a>
                            </td>
                        </tr>
                        <tr class="hide">
                            <td>
                            Reply to applicant directly: mantas@mantas.co or visit full profile: http://www.globalcastingcenter.com/talent/jack-bolton
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table class="hide" style="font-size: 12px; display:none;">
                    <tbody>
                        <tr class="hide">
                            <td><strong>Short Profile Summary:</strong></td>
                        </tr>
                    </tbody>
                </table>
                <table class="hide" style="font-size: 12px; display:none;">
                    <tbody>
                        <tr class="hide">
                            <td>
                            <a href="http://www.globalcastingcenter.com/talent/jack-bolton"><img alt="" src="http://globalcastingcenter.com/talent_images/4164035_258551_foto.png?Action=thumbnail&amp;Width=144&amp;Height=215" /></a>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <table style="font-size: 12px; display:none;" class="hide">
                    <tbody>
                        <tr class="hide">
                            <td><strong>Areas:</strong></td>
                            <td>Actor,Extra</td>
                        </tr>
                        <tr class="hide">
                            <td><strong>Country:</strong></td>
                            <td>WORLDWIDE,Any</td>
                        </tr>
                        <tr class="hide">
                            <td><strong>Age:</strong></td>
                            <td>26</td>
                        </tr>
                    </tbody>
                </table>
                <!-- End Original Content -->

            </td>
        </tr>
    </tbody>
</table>
<!-- End Wrapper Table that Replaces <span> element -->


Here's the plugin code, it's called "cwjdsjcsconfineselection".

To add the plugin:
Create a folder called "cwjdsjcsconfineselection" in the plugins directory: ckeditor/plugins/
Create a file called "plugins.js" in that directory and paste the code below into that file. My mistake: file is named plugin.js, not plugin(s).js.

If you already have extra plugins, add "cwjdsjcsconfineselection" to the extraPlugins config setting, otherwise add this setting to your configuration:
config.extraPlugins = 'cwjdsjcsconfineselection';

The plugin should work the next time you load the editor.

For my situation, I have a dialog box appear when the user clicks in a non-editable area to explain why the cursor was moved back to the previous selection. That doesn't seem necessary for your usage, so I commented it out.

/*
  Plugin that prevents editing of elements with the "non-editable" class as well as elements outside of blocks with "editable" class.
*/

//* **************************  NOTES  ***************************  NOTES  ****************************
/*
  The "lastSelectedElement" variable is used to store the last element selected.

  This plugin uses the "elementspath" plugin which shows all elements in the DOM
  parent tree relative to the current selection in the editing area.

  When the selection changes, "elementsPathUpdate" is fired,
  we key on this and loop through the elements in the tree checking the classes assigned to each element.

  Three outcomes are possible.

  1) The non-editable class is found:
  Looping stops, the current action is cancelled and the cursor is moved to the previous selection.
  The "selectionChange" hook is fired to set the reverted selection throughout the instance.

  2) The editable class is found during looping, the "in_editable_area" flag is set to true.

  3) Neither the editable or the non-editable classes are found (user clicked outside your main container).
  The "in_editable_area" flag remains set to false.

  If the "in_editable_area" flag is false, the current action is cancelled and the cursor is moved to the previous location.
  The "selectionChange" hook is fired to set the reverted selection throughout the instance.

  If the "in_editable_area" flag is true,
  the "lastSelectedElement" is updated to the currently selected element and the plugin returns true.

---------------
  If you don't want the elements path to be displayed at the bottom of the editor window,
  you can hide it with CSS rather than disabling the "elementspath" plugin.

  The elementspath plugin creates and is left active because we are keying on changes to the path in our plugin.
  #cke_path_content
  {
    visibility: hidden !important;
  }

---------------
  CSS Classes and ID that the plugin keys on. Use defaults or update variables to use your preferred classes and ID:

  var starting_element_id = ID of known editable element that always occurs in the instance.
  Don't use elements like <table>, <tr>, <br /> that don't contain HTML text.
  Default value = cwjdsjcs_editable_id

  var editable_class = class of editable containers.
  Should be applied to all top level elements that contain editable elements.
  Default = cwjdsjcs_editable

  var non_editable_class = class of non-editable elements within editable containers
  Apply to elements where all child elements are non-editable.
  Default = cwjdsjcs_not_editable

*/

//* **************************  END NOTES  ***************************  END NOTES  ****************************


// Register the plugin with the editor.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.plugins.html
CKEDITOR.plugins.add( 'cwjdsjcsconfineselection',
{
  requires : [ 'elementspath' ],

  // The plugin initialization logic goes inside this method.
  // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.pluginDefinition.html#init
  init: function( editor )
  {
    editor.on( 'instanceReady', function( instance_ready_data )
    {
      // Create variable that will hold the last allowed selection (for use when a non-editable selection is made)
      var lastSelectedElement;
      editor.cwjdsjcs_just_updated = false;

      // This section starts things off right by selecting a known editable element.
      // *** Enter the ID of the element that should have initial focus *** IMPORTANT *** IMPORTANT ***
      var starting_element_id = "cwjdsjcs_editable_id";

      var resInitialRange = new CKEDITOR.dom.range( editor.document );

      resInitialRange.selectNodeContents( editor.document.getById( starting_element_id ) );
      resInitialRange.collapse();

      var selectionObject = new CKEDITOR.dom.selection( editor.document );

      editor.document.focus();
      selectionObject.selectRanges( [ resInitialRange ] );

      var sel = editor.getSelection();
      var firstElement = sel.getStartElement();
      var currentPath = new CKEDITOR.dom.elementPath( firstElement );

      // Set path for known editable element, fire "selectionChange" hook to update selection throughout instance.
      editor._.selectionPreviousPath = currentPath;
      editor.fire( 'selectionChange', { selection : sel, path : currentPath, element : firstElement } );
    }); // *** END - editor.on( 'instanceReady', function( e )


    // When a new element is selected by the user, check if it's ok for them to edit it,
    // if not move cursor back to last know editable selection
    editor.on( 'elementsPathUpdate', function( resPath )
    {
      // When we fire the "selectionChange" hook at the end of this code block, the "elementsPathUpdate" hook fires.
      // No need to check because we just updated the selection, so bypass processing.
      if( editor.cwjdsjcs_just_updated == true )
      {
        editor.cwjdsjcs_just_updated = false;
        return true;
      }

      var elementsList = editor._.elementsPath.list;
      var in_editable_area = false;
      var non_editable_class = "cwjdsjcs_not_editable";
      var editable_class = "cwjdsjcs_editable";

      for(var w=0;w<elementsList.length;w++){
        var currentElement = elementsList[w];

        // Sometimes a non content element is selected, catch them and return selection to editable area.
        if(w == 0)
        {
          // Could change to switch.
          if( currentElement.getName() == "tbody" )
          {
            in_editable_area = false;
            break;
          }

          if( currentElement.getName() == "tr" )
          {
            in_editable_area = false;
            break;
          }
        }

        // If selection is inside a non-editable element, break from loop and reset selection.
        if( currentElement.hasClass(non_editable_class) )
        {
          in_editable_area = false;
          break;
        }

        if( currentElement.hasClass(editable_class) ) {
          in_editable_area = true;
        }
        console.log(currentElement);
        console.log(currentElement.getName());
      }

      // if selection is within an editable element, exit the plugin, otherwise reset selection.
      if( in_editable_area ) {
        lastSelectedElement = elementsList[0];
        return true;
      }

      var resRange = new CKEDITOR.dom.range( editor.document );

      resRange.selectNodeContents( lastSelectedElement );
      resRange.collapse();
      editor.getSelection().selectRanges( [ resRange ] );
      resRange.endContainer.$.scrollIntoView();

      // Open dialog window:
      // It tells user they selected a non-editable area and cursor has been returned to previous selection
//      currentEditorName = editor.name;
//      openResDefaultDialog(currentEditorName);

      try
      {
        var sel = editor.getSelection();
        var firstElement = sel.getStartElement();
        var currentPath = new CKEDITOR.dom.elementPath( firstElement );
        editor.cwjdsjcs_just_updated = true;

        editor._.selectionPreviousPath = currentPath;
        editor.fire( 'selectionChange', { selection : sel, path : currentPath, element : firstElement } );

      }
      catch (e)
      {}
    });
  } // *** END - init: function( editor )
}); // ************************************************************************************* END - CKEDITOR.plugins.add

To test that the plugin is loaded add an alert after the instance ready trigger:

    editor.on( 'instanceReady', function( instance_ready_data )
    {
      alert("instanceReady");

To test that the plugin is being triggered when the selection changes, add an alert after the elementsPathUpdate trigger:

    editor.on( 'elementsPathUpdate', function( resPath )
    {
      alert("elementsPathUpdate");

这篇关于如何阻止编辑CKEDITOR textarea中的某些部分内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆