我正在使用 CKEditor 来启用内联编辑数据。当我直接在 html 标签中使用 contenteditable 时,它工作得很好。但是,当我单击文档上的任何标签时,我会显式启用内联编辑,方法是在 JavaScript 中动态添加属性 contenteditable,然后在单击的标签上调用方法 CKEDITOR.inline('id')。在某些情况下它会产生意想不到的行为。
情况1:当所选标签的内容是纯文本时。效果很好。
情况2:当选中的标签内容包含多个标签如<strong>
时, <b>
。 CKEditor 工具栏不出现,有时所有 html 都会崩溃。
Please click here to view the behavior (JSFiddle)
HTML 代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.2/ckeditor.js"></script>
<div>
<p> This is the the paragraph with out any other tag. </p>
<p> This is the the paragraph with a link tag <a href="#">link</a> </p>
<p> This is the the paragraph with a bold tag <b>bold</b> </p>
</div>
JavaScript 代码
$(document).ready(function(e){
$(document).click(function(event){
console.log("clicked: " + event.currentTarget);
// event.target is the clicked object
var view = $(event.target);
var uniqueIdforCurrentElement = randomString(32).trim();
if(view.attr('id') === undefined || view.attr('id') === ''){
view.attr('id', uniqueIdforCurrentElement);
} else {
uniqueIdforCurrentElement = view.attr('id');
}
var editor = CKEDITOR.instances[uniqueIdforCurrentElement];
// console.log(uniqueIdforCurrentElement, editor);
if (editor) {
editor.destroy(true);
}
view.attr('contenteditable', true);
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline(view.get(0));
});
});
最佳答案
我认为内联编辑器只允许使用 div 或 textarea 标签。请尝试以下操作:
使用类名为“ckContainer”的 div 标签包围所有可编辑区域。然后用这个类名在父div中初始化CKeditor。我已经测试过它并且有效。
问候,安德烈亚斯。
$(document).ready(function(e) {
$(document).click(function(event) {
console.log("clicked: " + event.currentTarget);
// event.target is the clicked object
var view = $(event.target);
var viewParentDiv = view.parent(".ckContainer");
var uniqueIdforCurrentElement = Math.random().toString();
if (viewParentDiv.attr('id') === undefined || viewParentDiv.attr('id') === '') {
viewParentDiv.attr('id', uniqueIdforCurrentElement);
} else {
uniqueIdforCurrentElement = view.attr('id');
}
var editor = CKEDITOR.instances[uniqueIdforCurrentElement];
// console.log(uniqueIdforCurrentElement, editor);
if (editor) {
editor.destroy(true);
}
viewParentDiv.attr('contenteditable', true);
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline(viewParentDiv.get(0));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ckeditor/4.2/ckeditor.js"></script>
<div>
<div class="ckContainer"><p> This is the the paragraph with out any other tag. </p></div>
<div class="ckContainer"><p> This is the the paragraph with a link tag <a href="#">link</a> </p></div>
<div class="ckContainer"><p> This is the the paragraph with a bold tag <b>bold</b> </p></div>
</div>
关于javascript - 使用 CKEditor 进行内联编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33647816/