在 CKEditor 中仅添加一次 HTML 元素
Add an HTML element only once in CKEditor
在我的 ckeditor 实例中,我想让我的用户插入一条水平线,但只能插入一次。如果存在现有行,则应将其替换为新行(与 Wordpress 上的阅读更多功能相同)。如果我只希望保留最后一个 HR 标签,我可以让它工作,但是如果用户想要将他的 HR 标签插入文档中比现有标签更高的位置怎么办?
我在实例化时使用了一个变量(比如 savedContent)来存储默认内容(没有任何 HR)。按照 Set cursor to specific position in CKEditor 中的步骤,我的想法是使用 savedContent 变量将 CKEditor 内容恢复为默认的无 HR 内容,然后(使用范围或书签)在光标位置插入新的 HR。
这是代码:
CKEDITOR.on('instanceReady', function() {
$(".cke_button__horizontalrule").attr("title","End Preview here");
var savedContent = CKEDITOR.instances['pro_story'].getData();
$(".cke_button__horizontalrule").on("click",function(){
var ranges = editor.getSelection().getRanges();
CKEDITOR.instances['pro_story'].setData(savedContent);
editor.getSelection().selectRanges( ranges );
editor.insertHtml("<hr />");
});
});
现在这段代码的问题是,出于某种原因,它给了我以下错误:给定的范围不在文档中。
我该怎么办?
在插入新标签之前获取一组现有 <hr />
标签。然后,在插入新标签后删除所有这些标签。
let hrArray;
CKEDITOR.instances['pro_story'].on('beforeCommandExec', function(evt) {
if (evt.data.name == 'horizontalrule') {
hrArray = evt.editor.document.getElementsByTag('hr').toArray();
}
});
CKEDITOR.instances['pro_story'].on('afterCommandExec', function(evt) {
if (evt.data.name == 'horizontalrule') {
hrArray.forEach(el => el.remove());
}
});
在我的 ckeditor 实例中,我想让我的用户插入一条水平线,但只能插入一次。如果存在现有行,则应将其替换为新行(与 Wordpress 上的阅读更多功能相同)。如果我只希望保留最后一个 HR 标签,我可以让它工作,但是如果用户想要将他的 HR 标签插入文档中比现有标签更高的位置怎么办?
我在实例化时使用了一个变量(比如 savedContent)来存储默认内容(没有任何 HR)。按照 Set cursor to specific position in CKEditor 中的步骤,我的想法是使用 savedContent 变量将 CKEditor 内容恢复为默认的无 HR 内容,然后(使用范围或书签)在光标位置插入新的 HR。
这是代码:
CKEDITOR.on('instanceReady', function() {
$(".cke_button__horizontalrule").attr("title","End Preview here");
var savedContent = CKEDITOR.instances['pro_story'].getData();
$(".cke_button__horizontalrule").on("click",function(){
var ranges = editor.getSelection().getRanges();
CKEDITOR.instances['pro_story'].setData(savedContent);
editor.getSelection().selectRanges( ranges );
editor.insertHtml("<hr />");
});
});
现在这段代码的问题是,出于某种原因,它给了我以下错误:给定的范围不在文档中。
我该怎么办?
在插入新标签之前获取一组现有 <hr />
标签。然后,在插入新标签后删除所有这些标签。
let hrArray;
CKEDITOR.instances['pro_story'].on('beforeCommandExec', function(evt) {
if (evt.data.name == 'horizontalrule') {
hrArray = evt.editor.document.getElementsByTag('hr').toArray();
}
});
CKEDITOR.instances['pro_story'].on('afterCommandExec', function(evt) {
if (evt.data.name == 'horizontalrule') {
hrArray.forEach(el => el.remove());
}
});