2017-09-20 52 views
0

在我目前的项目中,用户可以用英文和希伯来语输入文本。 根据当前的文字,自动定义方向会很好。例如,如果文本包含希伯来语符号,则方向应该是RTL。但是如果文本不包含希伯来文,那么方向是LTR。如何在CKEditor中动态切换文本方向

文字可随时更改,我认为最好的解决方案是像在Google翻译服务中一样动态切换方向。

回答

0

我没有找到已经完成的解决方案,我想提出自己的解决方案。

它很简单。每当文本发生变化时,我都会检查希伯来文符号,如果需要,我会更改文本方向。要在配置中应用更改(在我的情况下它是文本的方向),我应该销毁并使用更新的配置初始化CKEditor。

如何测试它:

  1. 试着用英语键入一些
  2. 尝试键入希伯来语的东西,例如,“שם”
  3. 尝试删除希伯来语符号
  4. 你将看到编辑器中的方向将如何根据当前文本改变

这里是代码:

var CKEditorConfig = { 
 
    contentsLangDirection: 'ltr', 
 
    forcePasteAsPlainText: true 
 
    }, 
 
    editorInstance; 
 

 
(function() { 
 
    // Initialise editor. 
 
    function initEditor() { 
 
    editorInstance = CKEDITOR.replace('editor', CKEditorConfig); 
 
    editorInstance.on('contentDom', function() { 
 
     var body = this.document.getBody(); 
 

 
     // These listeners will be deactivated once editor dies. 
 
     // Input event to track any changes of the content 
 
     this.editable().attachListener(body, 'input', function() { 
 
     editorOnChange(); 
 
     }); 
 
    }); 
 
    } 
 
    
 
    // On change callback. 
 
    function editorOnChange() { 
 
    \t var text = CKEDITOR.instances['editor'].getData(), 
 
     direction = isHebrew(text) ? 'rtl' : 'ltr', 
 
     currentDirection = CKEditorConfig.contentsLangDirection; 
 

 
     // Direction was changed -> reinit CKEditor. 
 
     if (currentDirection && currentDirection != direction) {  \t 
 
     CKEditorConfig.contentsLangDirection = direction; 
 
     CKEDITOR.instances['editor'].destroy(); 
 
     editorInstance = initEditor(); 
 
     } 
 
    } 
 
    
 
    // Checks is current text uses hebrew language or not. 
 
    function isHebrew (text) { 
 
    const HebrewChars = new RegExp("[\u05D0-\u05FF]+"); 
 

 
    if (!HebrewChars.test(text)) { 
 
     return false; 
 
    } 
 
    return true; 
 
    } 
 
    
 
    // Init editor. 
 
    initEditor(); 
 

 
})();
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> 
 
<script src="https://cdn.ckeditor.com/4.7.1/basic/ckeditor.js"></script> 
 

 
<body> 
 
    <textarea id="editor" cols="50" rows="20"></textarea> 
 
</body>

似乎CKEditor的不能在这里启动。我看到一些错误。 您可以尝试正确启动它JSFiddle

一个问题:奇怪,但事件“输入”不会启动此复制粘贴在此示例中的操作,但在我当前的应用程序中工作。似乎库的版本是相同的。但这个例子并不重要。

我希望这会对某个人有用。