Ver Mensaje Individual
  #5 (permalink)  
Antiguo 25/11/2013, 14:38
Avatar de marlanga
marlanga
 
Fecha de Ingreso: enero-2011
Ubicación: Murcia
Mensajes: 1.024
Antigüedad: 13 años, 3 meses
Puntos: 206
Respuesta: Seleccionar frase y colocar BBCodes

Deja los temas puramente difíciles para los que sabemos programar, phperos.

http://jsfiddle.net/4bthd/

Código HTML:
Ver original
  1. <button id="btnNegritas"><b>b</b></button>
  2. <button id="btnCursiva"><i>i</i></button>
  3. <button id="btnSubrayado"><u>u</u></button>
  4. <br/>
  5. <textarea id="campo"></textarea>

Código Javascript:
Ver original
  1. window.onload=function(){
  2.     var Editor={
  3.         textarea:document.getElementById("campo"),
  4.         negritas:document.getElementById("btnNegritas"),
  5.         cursiva:document.getElementById("btnCursiva"),
  6.         subrayado:document.getElementById("btnSubrayado"),
  7.         insertar:function(bbcode){
  8.             var texto=Editor.textarea.value,
  9.                 inicio=Editor.textarea.selectionStart,
  10.                 fin=Editor.textarea.selectionEnd;
  11.            
  12.             texto=texto.slice(0,inicio)+"["+bbcode+"]"+texto.slice(inicio,fin)+"[\\"+bbcode+"]"+texto.slice(fin);
  13.             Editor.textarea.value=texto;
  14.         }
  15.     };
  16.     Editor.negritas.onclick=function(){
  17.         Editor.insertar("b");
  18.     };
  19.     Editor.cursiva.onclick=function(){
  20.         Editor.insertar("i");
  21.     };
  22.     Editor.subrayado.onclick=function(){
  23.         Editor.insertar("u");
  24.     };
  25. };

Básicamente el código es una tontería, escrito en 5 minutos. Sólo es necesario saber cómo se cortan cadenas en javascript y cómo se recupera el texto seleccionado de cualquier elemento.