如何强制CKEditor内联窗口小部件来保留尾随空格

时间:2017-07-05 08:17:05

标签: ckeditor

正如我在CKEditor this ticket报道的那样,CKEditor(4.7.0)中的内联小部件不保留尾随空格,导致显示问题。

采用以下简单小部件:

CKEDITOR.plugins.add('spanwidget', {
    requires: 'widget',
    init: function (editor)    {
        editor.widgets.add('spanwidget', {
            editables: {
                content: {
                    selector: 'span'
              }
            },
            upcast: function (element) {
                return element.name == 'span';
            }
        });
    }
});

当您加载以下数据<span>lorem </span>ipsum时,您会在输出中看到此文字:loremipsum(注意缺少的空格)。

可以看到in this JSFiddle

如何解决问题(我不控制在CKEditor中加载哪些数据)?

1 个答案:

答案 0 :(得分:0)

我找到了一种解决方法来强制保留最后的尾随空格。我们的想法是在向上转换窗口小部件元素时用&nbsp;替换最后一个空格,然后在向下转换它之前将其删除:

CKEDITOR.replace('ck', {
  allowedContent: true,
  extraPlugins: 'spanwidget'
});

CKEDITOR.plugins.add('spanwidget', {
    requires: 'widget',
    init: function (editor) {
      editor.widgets.add('spanwidget', {
        editables: {
          content: { selector: 'span' }
        },
        upcast: function (element) {
          // Matches?
          if (element.name == 'span') {
            // Ends with text?
            var children = element.children,
              childCount = children.length,
              lastChild = childCount && children[childCount - 1];
            if (lastChild instanceof CKEDITOR.htmlParser.text) {
              // Replace the last space with a non breaking space
              // (see https://github.com/ckeditor/ckeditor-dev/issues/605)
              lastChild.value = lastChild.value.replace(/ $/, '&nbsp;');
            }
            // Match!
            return true;
          }
          // No match
          return false;
        },
        downcast: function (element) {
          // Span with class "targetinfo"?
          if (element.name == 'span') {
            // Ends with text?
            var children = element.children,
              childCount = children.length,
              lastChild = childCount && children[childCount - 1];
            if (lastChild instanceof CKEDITOR.htmlParser.text) {
              // Ends with a non breaking space?
              var match = lastChild.value.match(/&nbsp;$/i);
              if (match) {
                // Replace the non breaking space with a normal one
                lastChild.value = lastChild.value.replace(/&nbsp;$/i, ' ');
                // Clone the element
                var clone = element.clone();
                // Reinsert all the children into that element
                for (var i = 0; i < childCount; i++) {
                  clone.add(children[i]);
                }
                // Return the clone
                return clone;
              }
            }
          }
        }
    });
  }
});

请参阅updated JSFiddle here