【问题标题】:How can I modify pasted text?如何修改粘贴的文本?
【发布时间】:2010-09-03 23:14:46
【问题描述】:

是否可以截取和修改粘贴到文本区域的文本?

如果不能拦截,粘贴后可以修改吗? (不修改文本区域中已经存在的文本。)

【问题讨论】:

  • 你在使用任何 javascript 库(例如 jQuery)吗?
  • @Adrian:我的问题更多是关于它是否可能,因此你可以假设任何你想要的库。

标签: jquery html dom


【解决方案1】:

使用 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

【讨论】:

  • 实际上 onpaste 事件在 Gecko 1.9.0.19 (Camino 2.0.4) 中有效。我认为它已在 Firefox 3 中引入,这是 mozilla 页面:developer.mozilla.org/en/DOM/element.onpaste 但是,没有很好的方法来获取粘贴的数据。
  • 啊,谢谢不知道 Firefox 3 实现了 onpaste,但是你不能用它来获取数据,这很糟糕。
  • 关于修改数据的信息在哪里?
  • 这不是对所提问题的回答。这是正确答案:stackoverflow.com/questions/43438665/…
【解决方案2】:

也许拦截keypresses,知道何时按下CTRL+C,缓存当前文本,然后在CTRL+Ckeyup,根据缓存的值检查当前值,通过简单的文本处理,您可以知道新文本,并随心所欲地进行相应的更新。

【讨论】:

【解决方案3】:

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

<script language="javascript">

function testfunction()
{

 // This function will execute whenever the content of 

}
</script>

<textarea onkeyup="testfunction()" onkeydown="testfunction()"></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>

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

【讨论】:

  • 考虑使用“setTimeout(monitor, 100);”而不是“setTimeout('monitor()', 100);”。评估是邪恶的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多