如何修改粘贴的文本?

如何修改粘贴的文本?

问题描述:

是否可以截取和修改粘贴到textarea中的文本?如何修改粘贴的文本?

如果拦截不可行,我可以在粘贴后修改它吗? (在不修改在textarea的已经存在的文本。)

+0

你使用任何JavaScript库(如jQuery)? – 2010-09-03 23:26:30

+1

@Adrian:我的问题更多的是如果它甚至是可能的,因此你可以假设你想要的任何图书馆。 – 2010-09-04 07:48:04

使用jQuery:

jQuery(function($){ 
     $('#your_element').bind('paste', function(event){ 
     event.preventDefault(); 
     var clipboardData = event.originalEvent.clipboardData.getData('text/plain'); 
     console.log(clipboardData); 
     }); 
    }  
    }); 

在IE和Webkit。与Firefox,您可能需要使用:

http://intridea.com/2007/12/16/faking-onpaste-in-firefox?blog=company

+0

事实上,onpaste事件在Gecko 1.9.0.19(Camino 2.0.4)中起作用。我认为它已经在Firefox 3中引入,这里是mozilla页面:https://developer.mozilla.org/zh/DOM/element.onpaste然而,没有好的方法来获取粘贴的数据。 – 2010-09-04 08:48:22

+0

啊,谢谢你不知道火狐3是在牙膏上实现的,但它很糟糕,你无法用它获取数据。 – Carlos 2010-09-04 16:20:58

+6

**有关** modyfing **数据的信息在哪里? – Mike 2017-02-09 01:28:40

也许截距keypress ES,知道当按压CTRL + Ç,高速缓存当前文本,则在CTRL + Çkeyup ,检查缓存的当前值,通过简单的文本处理,您可以了解新文本,并根据需要进行相应的更新。

+0

我不确定这适用于所有浏览器,但绝对是我认为更好的方法。 http://api.jquery.com/keypress/ – userx 2010-09-04 03:39:19

我知道如何做到这一点的最好方法是等待文本字段的内容被粘贴,然后等待keyup或keydown触发器。这显示在下面的代码:

<script language="javascript"> 

function testfunction() 
{ 

// This function will execute whenever the content of 

} 
</script> 

<textarea onkeyup="testfunction()" onkeydown="testfunction()"></textarea> 

如果要监视任何改变一个textarea,下面的代码将做到这一点。它会每1/10秒检查一次textarea的值是否有更新。

<textarea id="testfield"></textarea> 

<script language="javascript"> 

var textarea = document.getElementById('testfield'); 
var textval = ''; 

function monitor() 
{ 

if(textval != textarea.value) 
{ 

    textval = textarea.value; 
    testfunction(); 

} 

setTimeout('monitor()', 100); 

} 

function testfunction() 
{ 

// This function will get executed whenever the value of the text area is altered (at most within 1/10th of a second) 

} 

monitor(); 
</script> 

在这两种情况下,你可以修改textarea的值时testfunction(),然后更新与更新值textarea的价值。

+2

考虑使用“setTimeout(monitor,100);”而不是“setTimeout('monitor()',100);”。 Eval是邪恶的:) – userx 2010-09-04 03:37:24