2012-12-15 22 views
16

Ho un semplice evento passato comeCome avvisare dopo l'evento paste in Javascript?

document.getElementById('paste_area').addEventListener('paste', function() { 
    document.getElementById('notice').innerHTML='Text was successfully pasted!'; 
    alert('Pasted'); 
}, true); 

Un esempio di lavoro può essere trovato qui http://jsfiddle.net/XEQzz/

L'allarme e l'avviso verrà visualizzato prima di incollare. Come posso ritardare l'azione di avviso per accadere dopo che l'evento Incolla è stato effettivamente completato?

+1

Usa 'setTimeout' (con un ritardo minimo come zero) rinviare l'esecuzione della sceneggiatura. –

+1

è possibile impostare il proprio gestore di incolla utilizzando preventDefault() (o variabile equivalente IE - ho dimenticato il nome), ma un modo più semplice è utilizzare un evento di input http://stackoverflow.com/a/241158/1162141 poiché (IIRC) può anche gestire il trascinamento del testo trascinato – technosaurus

+0

@technosaurus 'paste handler' non è a prova di proiettile e cross-browser. Ad esempio, FireFox non consente l'accesso ai dati di incolla. – Googlebot

risposta

24

È possibile inserire l'avviso in un setTimeout.

setTimeout(function() {alert('Pasted');}, 0); 

Ciò ritarderà il codice fino a dopo che il valore è stato aggiornato.

Basta ricordare che this nella callback setTimeout avrà un valore diverso da quello nell'ambiente di chiusura.

Se avrete bisogno di un riferimento alla esterno this, che sarà l'elemento, quindi fare riferimento in una variabile ...

var self = this; 
setTimeout(function() {alert(self.value);}, 0); 

Oppure utilizzare .bind()(supportato nella maggior parte dei browser che supportano addEventListener . vecchio Safari non supporta.) ...

setTimeout(function() {alert(this.value);}.bind(this), 0); 
+0

"questo" è diverso! Questo mi ha salvato, grazie, buona spiegazione :) – Maximosaic

+0

È un hack ma ad una riga è un bellissimo trucco! Per me funziona. Grazie ;) – Zeek

3

setTimeout sembra l'opzione migliore e si può usare qualcosa di simile a generalizzare

// oggetto definizione

function PasteMonitor(element) 
    { 
     if(typeof element == "string") 
     { 
      this.target = document.getElementById(element); 
     } 
     else if(typeof element == "object" || typeof element == "function") 
     { 
      this.target = element; 
     } 

     if(this.target != null && this.target != undefined) 
     { 
      this.target.addEventListener('paste',this.inPaste.bind(this),false); 
      this.target.addEventListener('change',this.changed.bind(this),false); 
     } 
     this.oldstate = ""; 
    } 
    PasteMonitor.prototype = Object.create({},{ 
     pasted:{ value: false, enumerable: true, configurable: true, writable: true }, 
     changed:{ value: function(evt){ 
      //elements content is changed 
      if(typeof this.onChange == "function") 
      { 
       this.onChange(evt); 
      } 
      if(this.pasted) 
      { 
       if(typeof this.afterPaste == "function") 
       { 
        this.afterPaste(evt); 
        this.pasted = false; 
       } 
      } 
     }, enumerable: true, configurable: true, writable: true }, 
     inPaste:{ value: function(evt){ 
      var cancelPaste = false; 
      if(typeof this.beforePaste == "function") 
      { 
       // process pasted data 
       cancelPaste = this.beforePaste(evt); 
      } 
      if(cancelPaste == true) 
      { 
       evt.preventDefault(); 
       return false; 
      } 
      this.pasted = true; 
      setTimeout(function(){ 
       var evt = document.createEvent("HTMLEvents"); 
       evt.initEvent("change", false, true); 
       this.target.dispatchEvent(evt); 
      }.bind(this),0); 
     }, enumerable: true, configurable: true, writable: true } 
    }) 
    PasteMonitor.prototype.constructor = PasteMonitor; 

// PasteMonitor utilizzo

//var element = document.getElementById('paste_area'); 
    var msgArea = document.getElementById('message'); 
    var myMonitor = new PasteMonitor("paste_area"); 
    //or use and object as argument => var myMonitor = new PasteMonitor(element); 

    myMonitor.onChange = function(evt){ 
     if(this.pasted) 
     { 
      //do something on paste change 
      msgArea.innerHTML = "onChange by paste"; 
      this.oldstate = this.target.value; 
     } 
     //check to prevent processing change event when the element loses focus if the change is done by paste 
     else if(this.target.value != this.oldstate) 
     { 
      msgArea.innerHTML = "onChange by typing"; 
     } 
    }; 
    myMonitor.afterPaste = function(evt){ 
     // do something after paste 
     msgArea.innerHTML = "afterPaste"; 
    }; 
    myMonitor.beforePaste = function(evt){ 
     // do something before the actual paste 
     msgArea.innerHTML = "beforePaste"; 
     //return true to prevent paste 
     return false; 
    }; 
0

Per l'aggiornamento proprio valore

$(".number").on("paste", function (e) { 
     var Value = e.originalEvent.clipboardData.getData('text'); 
     var Self=this 
     setTimeout(function() { 
      if (Value != Value.replace(/[^\d\.]/g, "")) { 
       $(Self).val(Value.replace(/[^\d\.]/g, "")); 
      } 
     }, 0); 
    }); 
Problemi correlati