Pregunta

¿Cómo puedo insertar texto / código en el lugar cursores en un div creado por NicEdit?

he tratado de leer la documentación y crear mi propio plugin, pero yo quiero que funcione sin la barra de herramientas (Ventana modal)

¿Fue útil?

Solución

Esta es una solución rápida y probado en solamente Firefox. Pero funciona y debe ser adaptable para IE y otros navegadores.

function insertAtCursor(editor, value){
    var editor = nicEditors.findEditor(editor);
    var range = editor.getRng();                    
    var editorField = editor.selElm();
    editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
                            value +
                            editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
}

Otros consejos

La forma en que esto era resuelto a hacer que el NicEdit Instancia div lanzables, usando jQuery UI; sino también para hacer que todos los elementos dentro de la lanzables div.

$('div.nicEdit-main').droppable({
    activeClass: 'dropReady',
    hoverClass: 'dropPending',
    drop: function(event,ui) {
    $(this).find('.cursor').removeClass('cursor');
  },
  over: function(event, ui) {
    if($(this).find('.cursor').length == 0) {
      var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
      $(this).append(insertEl);
    }
  },
  out: function(event, ui) {
    $(this).find('.cursor').remove();
  },
  greedy: true
});

$('div.nicEdit-main').find('*').droppable({
  activeClass: 'dropReady',
  hoverClass: 'dropPending',
  drop: function(event,ui) {
    $(this).find('.cursor').removeClass('cursor');
  },
  over: function(event, ui) {
    var insertEl = $('<span class="cursor"/>').append($(ui.draggable).attr('value'));
    $(this).append(insertEl);
  },
  out: function(event, ui) {
    $(this).find('.cursor').remove();
  },
  greedy: true
});

A continuación, hacer que el código o el texto se pueda arrastrar:

$('.field').draggable({
                appendTo: '.content', //This is just a higher level DOM element
                revert: true,
                cursor: 'pointer',
                zIndex: 1500, // Make sure draggable drags above everything else
                containment: 'DOM',
                helper: 'clone' //Clone it while dragging (keep original intact)
            });            

Entonces, finalmente, asegúrese de que establece el valor del elemento que pueden arrastrarse a lo que usted desea insertar y / o modificar el código de abajo para insertar el elemento (intervalo) de su elección.

        $sHTML .= "<div class='field' value='{{".$config[0]."}}'>".$config[1]."</div>";

Insertar HTML Plugin

No sé si esto ayuda o no, pero esto es el plugin que he creado para insertar HTML en la posición del cursor. El botón abre un panel de contenido y acabo de pegar en el HTML que quiero y Enviar. Obras para mí!

var nicMyhtmlOptions = {
    buttons : {
      'html' : {name : 'Insert Html', type : 'nicMyhtmlButton'}
    },iconFiles : {'html' : '/nicedit/html_add.gif'}

};

var nicMyhtmlButton=nicEditorAdvancedButton.extend({
      addPane: function () {
      this.addForm({
        '': { type: 'title', txt: 'Insert Html' },
        'code' : {type : 'content', 'value' : '', style : {width: '340px', height : '200px'}}
      });
    },

    submit : function(e) {
      var mycode = this.inputs['code'].value;
      this.removePane();
      this.ne.nicCommand('insertHTML', mycode );
    }

});
nicEditors.registerPlugin(nicPlugin,nicMyhtmlOptions);

I utiliza el icono html_add de seda iconos , pegado sobre una transparente 18 x 18 y guardado como gif en la misma carpeta que nicEditorIcons.gif.

A mí me funciona cuando uso:

function neInsertHTML(value){
    $('.nicEdit-main').focus(); // Without focus it wont work!
    // Inserts into first instance, you can replace it by nicEditors.findEditor('ID');
    myNicEditor.nicInstances[0].nicCommand('InsertHTML', value); 
}

Una respuesta a @Reto: Este código funciona, sólo tenía que añadir un poco de solución, ya que no hace nada si inserto área de texto está vacía. También se añade sólo texto sin formato. Aquí está el código si alguien lo necesite:

if(editorField.nodeValue==null){
  editor.setContent('<strong>Your content</strong>');
}else{        
  editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
                          '<strong>Your content</strong>' +
                          editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
  editor.setContent(editorField.nodeValue);
}

Cambiar follwoing en NicEdit.js Archivo

Actualización del Reto Aebersold Ans Que se encargará de excepción nulo nodo, si el área de texto está vacía

update: function (A) {
    (this.options.command);
        if (this.options.command == 'InsertBookmark') {
            var editor = nicEditors.findEditor("cpMain_area2");
            var range = editor.getRng();
            var editorField = editor.selElm();
            //  alert(editorField.content);
            if (editorField.nodeValue == null) {
                //  editorField.setContent('"' + A + '"')
                var oldStr = A.replace("<<", "").replace(">>", "");
                editorField.setContent("&lt;&lt;" + oldStr + "&gt;&gt;");
            }
            else {
                // alert('Not Null');
                // alert(editorField.nodeValue + '  ' + A);
                editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) + A + editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);
            }
        }
        else {
            // alert(A);  
            /* END HERE */
            this.ne.nicCommand(this.options.command, A);
        }

Este trabajo función cuando NicEdit área de texto está vacío o el cursor se encuentra en el espacio en blanco o nueva línea.

function addToCursorPosition(textareaId,value) {
            var editor = nicEditors.findEditor(textareaId);
            var range = editor.getRng();
            var editorField = editor.selElm();
            var start = range.startOffset;
            var end = range.endOffset;
            if (editorField.nodeValue != null) {
                editorField.nodeValue = editorField.nodeValue.substring(0, start) +
                            value +
                            editorField.nodeValue.substring(end, editorField.nodeValue.length);
            }
            else {
                var content = nicEditors.findEditor(textareaId).getContent().split("<br>");
                var linesCount = 0;
                var before = "";
                var after = "";
                for (var i = 0; i < content.length; i++) {
                    if (linesCount < start) {
                        before += content[i] + "<br>";
                    }
                    else {
                        after += content[i] + "<br>";
                    }
                    linesCount++;
                    if (content[i]!="") {
                        linesCount++;
                    }
                }
                nicEditors.findEditor(textareaId).setContent(before + value + after);
            }

        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top