2013-03-13 2 views
4

Я использую nicEdit, чтобы иметь текстовое поле RTF, и мне нужно добавить , onkeyup или onkeydown.nicEdit: Добавить ключ (нажмите | вверх | вниз) события в редакторе

Я создаю мой экземпляр так:

var emailRtf = new nicEditor({ iconsPath : 'nicEdit/nicEditorIcons.gif', 
    buttonList : ['bold','italic','underline','fontSize','forecolor','ol','ul','link','unlink','removeformat'], 
    maxHeight: 600}).panelInstance('REPLY_MESSAGE'); 

Я попробовал следующее (с keypress, keydown и keyup):

emailRtf.addEvent("keypress", function() { alert('test') }); // Not working 
emailRtf.addEvent("keypress", function(evt) { alert('test') }); // Not working 

Однако следующие работы:

emailRtf.addEvent("blur", function() { alert('test') }); // Alert shows when I leave focus on the textArea 

Как добавить key(press|up|down) в редактор nicEdit?

ПРИМЕЧАНИЕ: У меня есть несколько экземпляров RTF textarea на моей странице, и мне нужно добавить событие key(press|down|up) только одному. Я нашел this вопрос, который добавляет событие во все экземпляры. Кроме того, я хотел бы оставить nicEdit.js неповрежденным.

ответ

5

Посмотрите здесь Limit the number of characters in a WYSIWYG Editor (NicEdit)

он должен работать без изменений в nicedit.js

$("div.nicEdit-main").keyup(function() { }); 

Посмотрите на jsfiddle http://jsfiddle.net/jGLRn/15/

+1

Works! Без jQuery: document.getElementById ('REPLY_MESSAGE'). ParentElement.onkeypress = function() {alert ('нажата клавиша!'); }; ' –

+1

@SimonArsenault Спасибо за ответ« без jquery ». Это отлично работает и сохраняет NicEdit легким – AlbatrossCafe

0

После дня исследования я не мог этого сделать без изменения nicEdit.js. Однако мне удалось сделать очень мало изменений. Вот они (я использую версию 0.9r24):

Я добавил один вариант конфигурации с именем customKeyDownFunction. По умолчанию он ничего не делает.

var nicEditorConfig = bkClass.extend({ 
    buttons : { 
     'bold' : {name : __('Click to Bold'), command : 'Bold', tags : ['B','STRONG'], css : {'font-weight' : 'bold'}, key : 'b'}, 
     'italic' : {name : __('Click to Italic'), command : 'Italic', tags : ['EM','I'], css : {'font-style' : 'italic'}, key : 'i'}, 
     'underline' : {name : __('Click to Underline'), command : 'Underline', tags : ['U'], css : {'text-decoration' : 'underline'}, key : 'u'}, 
     'left' : {name : __('Left Align'), command : 'justifyleft', noActive : true}, 
     'center' : {name : __('Center Align'), command : 'justifycenter', noActive : true}, 
     'right' : {name : __('Right Align'), command : 'justifyright', noActive : true}, 
     'justify' : {name : __('Justify Align'), command : 'justifyfull', noActive : true}, 
     'ol' : {name : __('Insert Ordered List'), command : 'insertorderedlist', tags : ['OL']}, 
     'ul' : {name : __('Insert Unordered List'), command : 'insertunorderedlist', tags : ['UL']}, 
     'subscript' : {name : __('Click to Subscript'), command : 'subscript', tags : ['SUB']}, 
     'superscript' : {name : __('Click to Superscript'), command : 'superscript', tags : ['SUP']}, 
     'strikethrough' : {name : __('Click to Strike Through'), command : 'strikeThrough', css : {'text-decoration' : 'line-through'}}, 
     'removeformat' : {name : __('Remove Formatting'), command : 'removeformat', noActive : true}, 
     'indent' : {name : __('Indent Text'), command : 'indent', noActive : true}, 
     'outdent' : {name : __('Remove Indent'), command : 'outdent', noActive : true}, 
     'hr' : {name : __('Horizontal Rule'), command : 'insertHorizontalRule', noActive : true} 
    }, 
    iconsPath : '../nicEditorIcons.gif', 
    buttonList : ['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor'], 
    iconList : {"bgcolor":1,"forecolor":2,"bold":3,"center":4,"hr":5,"indent":6,"italic":7,"justify":8,"left":9,"ol":10,"outdent":11,"removeformat":12,"right":13,"save":24,"strikethrough":15,"subscript":16,"superscript":17,"ul":18,"underline":19,"image":20,"link":21,"unlink":22,"close":23,"arrow":25}, 
    customKeyDownFunction : function() { } 
}); 

Я модифицировал функцию KeyDown.

keyDown : function(e,t) { 
    this.ne.options.customKeyDownFunction(); 

    if(e.ctrlKey) { 
     this.ne.fireEvent('key',this,e); 
    } 
} 

Когда я создаю свой экземпляр nicEditor, я определяю customKeyDownFunction.

var emailRtf = new nicEditor({ 
     iconsPath : 'nicEdit/nicEditorIcons.gif', 
     buttonList : ['bold','italic','underline','fontSize','forecolor','ol','ul','link','unlink','removeformat'], 
     maxHeight: 600, 
     customKeyDownFunction: function() { alert('key down!'); } 
    }).panelInstance('REPLY_MESSAGE'); 

Если вам не нужны какие-либо пользовательские функции, просто не определяют customKeyDownFunction.

var emailRtf = new nicEditor({ 
     iconsPath : 'nicEdit/nicEditorIcons.gif', 
     buttonList : ['bold','italic','underline','fontSize','forecolor','ol','ul','link','unlink','removeformat'], 
     maxHeight: 600 
    }).panelInstance('REPLY_MESSAGE'); 

Это лучшее, что я мог бы сделать. Если у кого-то есть лучший способ, скажите!

2

Read the official documentation here. Он показывает вам, как связать (их) поддерживаются события в вашей nicEdit например без использования JQuery:

var commentNicEditor = new nicEditor().panelInstance('comment'); 
commentNicEditor.addEvent("blur", function() { 
    // Sent when an editor instance loses focus  
}); 
commentNicEditor.addEvent("focus", function() { 
    // Send when an editor gains focus (IE someone clicks inside it)  
}); 
commentNicEditor.addEvent("key", function() { 
    // When the user presses a shortcut key (Such as control-b)  
}); 
commentNicEditor.addEvent("add", function() { 
    // Fired when a new instance is added  
}); 
commentNicEditor.addEvent("panel", function() { 
    // Fired when the toolbar is initialized for new instances (This is the preferred event if you want to add a function when NicEdit instances are created)  
}); 
+1

'commentNicEditor.addEvent («ключ», функция() { // Когда пользователь нажимает клавишу быстрого доступа (например, control-b) }); ' Это только для сочетаний клавиш, поэтому это не сработает. –

+0

@SimonArsenault на самом деле является частью официальной документации о том, как связать события, фактически не используя 'jQuery', поскольку вопрос не помечен' jQuery'. –

+1

Я знаю это, но если вы его читаете, он четко говорит «Горячие клавиши (такие как control-b)». Он не может использоваться для записи всех клавиш, таких как onkeypress. Я считаю, что единственный способ - это принятый ответ (без jQuery в комментариях) или путем прямого изменения источника кода (уродливый путь). –

Смежные вопросы