2010-07-09 30 views
13

¿Cómo detectar qué texto pega el usuario en textarea con JS?Detectar texto pegado con ctrl + v o hacer clic con el botón derecho -> pegar

+2

posible duplicado de [¿Cómo detecta facebook cuando un enlace como ha pegado] (http://stackoverflow.com/questions/1891145/how-does-facebook-detect-when- a-link-as-been-pegado) –

+0

No, por ejemplo, pego "test textarea", quiero detectar qué texto está pegado, en este caso - "test textarea" – lam3r4370

+0

probablemente no puedas hacer ese cross-browser ... – galambalazs

Respuesta

16

Se podría utilizar el evento pasta para detectar la pasta en la mayoría de los navegadores (especialmente no en Firefox 2, aunque). Cuando maneje el evento pegar, grabe la selección actual, y luego configure un breve temporizador que llame a una función después de que se haya completado el pegado. Esta función puede comparar longitudes y saber dónde buscar el contenido pegado. Algo como lo siguiente. En aras de la brevedad, la función que obtiene la selección de texto no funciona en IE. Vea aquí algo que hace: How to get the start and end points of selection in text area?

function getTextAreaSelection(textarea) { 
    var start = textarea.selectionStart, end = textarea.selectionEnd; 
    return { 
     start: start, 
     end: end, 
     length: end - start, 
     text: textarea.value.slice(start, end) 
    }; 
} 

function detectPaste(textarea, callback) { 
    textarea.onpaste = function() { 
     var sel = getTextAreaSelection(textarea); 
     var initialLength = textarea.value.length; 
     window.setTimeout(function() { 
      var val = textarea.value; 
      var pastedTextLength = val.length - (initialLength - sel.length); 
      var end = sel.start + pastedTextLength; 
      callback({ 
       start: sel.start, 
       end: end, 
       length: pastedTextLength, 
       text: val.slice(sel.start, end) 
      }); 
     }, 1); 
    }; 
} 

var textarea = document.getElementById("your_textarea"); 
detectPaste(textarea, function(pasteInfo) { 
    alert(pasteInfo.text); 
    // pasteInfo also has properties for the start and end character 
    // index and length of the pasted text 
}); 
+0

¡Muchas gracias! – lam3r4370

+0

¿Esta encuesta es cada 1 milisegundo? – chug2k

+0

@ chug2k: No, solo ejecuta esa función después de 1 milisegundo (o lo que sea que implemente el navegador en su lugar) una vez después de cada pegado. –

1

siguiente puede ayudarle a

function submitenter(myfield,e) 
    { 
    var keycode; 
    if (window.event) keycode = window.event.keyCode; 
    else if (e) keycode = e.which; 
    else return true; 
    if (keycode == //event code of ctrl-v) 
    { 
     //some code here 
    } 

    } 

    <teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea> 
+1

Sí, pero ¿cuál será el lugar de "algún código aquí" si deseo detectar qué texto pega el usuario? – lam3r4370

1

funciona en IE 8 - 10

Creación de código personalizado para que el comando Pegar requiere varios pasos.

  1. Establezca el objeto de evento returnValue en false en el evento onbeforepaste para habilitar la opción de menú Pegar acceso directo.
  2. Cancele el comportamiento predeterminado del cliente estableciendo el objeto de evento returnValue en false en el controlador de eventos onpaste. Esto se aplica solo a los objetos, como el cuadro de texto, que tienen un comportamiento predeterminado definido para ellos.
  3. Especifique un formato de datos en el que pegar la selección mediante el método getData del objeto clipboardData.
  4. invoque el método en el evento onpaste para ejecutar código de pegado personalizado.

Para invocar este caso, realice una de las siguientes opciones:

  • derecho del ratón para mostrar el menú contextual y seleccione Pegar.
  • O presione CTRL + V.

Ejemplos

<HEAD> 
<SCRIPT> 
var sNewString = "new content associated with this object"; 
var sSave = ""; 
// Selects the text that is to be cut. 
function fnLoad() { 
    var r = document.body.createTextRange(); 
    r.findText(oSource.innerText); 
    r.select(); 
} 
// Stores the text of the SPAN in a variable that is set 
// to an empty string in the variable declaration above. 
function fnBeforeCut() { 
    sSave = oSource.innerText; 
    event.returnValue = false; 
} 
// Associates the variable sNewString with the text being cut. 
function fnCut() { 
    window.clipboardData.setData("Text", sNewString); 
} 
function fnBeforePaste() { 
    event.returnValue = false; 
} 
// The second parameter set in getData causes sNewString 
// to be pasted into the text input. Passing no second 
// parameter causes the SPAN text to be pasted instead. 
function fnPaste() { 
    event.returnValue = false; 
    oTarget.value = window.clipboardData.getData("Text", sNewString); 
} 
</SCRIPT> 
</HEAD> 
<BODY onload="fnLoad()"> 
<SPAN ID="oSource" 
     onbeforecut="fnBeforeCut()" 
     oncut="fnCut()">Cut this Text</SPAN> 
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here" 
     onbeforepaste="fnBeforePaste()" 
     onpaste="fnPaste()"> 
</BODY> 

documento completo: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx

7

HTML5 ya proporciona onpaste no sólo <input/>, pero también elementos editables (<p contenteditable="true" /> , ...)

<input type="text" onpaste="myFunction()" value="Paste something in here"> 

More info here

+2

Tenga cuidado, este no es un estándar web. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/onpaste. (también, MDN es mucho más confiable que W3Schools para API web) –

Cuestiones relacionadas