我怎么知道用户正在打字或粘贴? [英] How can I know user is typing or pasting?

查看:63
本文介绍了我怎么知道用户正在打字或粘贴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的JSP的文本字段中,我想知道用户是在输入数据还是只是粘贴。
如何使用javascript识别这个?

In text fields of my JSP, I wish to know whether user is typing in the data or just pasting. How can I identify this using javascript ?

编辑:根据Andy的回答,我知道如何解决这个问题,但是仍然好奇这些人如何写 onpaste 事件。

As per Andy's answer I know how I can go about it, but still curios how those guys wrote onpaste event.

推荐答案

Safari,Chrome,Firefox和Internet Explorer全部支持 onpaste 事件(不确定Opera)。锁定 onpaste 事件,只要粘贴了某些内容,您就可以捕获它。



写这个很简单。使用html将事件处理程序添加到输入中:

Safari, Chrome, Firefox and Internet Explorer all support the onpaste event (not sure about Opera). Latch onto the onpaste event and you will be able to catch whenever something is pasted.


Writing this is simple enough. Add the event handler to your input using html:

<input type="text" id="myinput" onpaste="handlePaste(event);">

或JavaScript-DOM:

or JavaScript-DOM:

var myInput = document.getElementById("myInput");

if ("onpaste" in myInput) // onpaste event is supported
{
    myInput.onpaste = function (e)
    {
        var event = e || window.event;
        alert("User pasted");
    }
}
// Check for mutation event support instead
else if(document.implementation.hasFeature('MutationEvents','2.0'))
{
    /* You could handle the DOMAttrModified event here, checking 
       new value length vs old value length but it wouldn't be 100% reliable */
}

根据我的阅读,Opera不支持 onpaste 事件。您可以使用 DOMAtrrModified 事件,但即使脚本更改了输入框的值,这也会触发,因此您必须小心它。不幸的是,我不熟悉变异事件所以我不想通过写一个我不自信的例子来弄清楚这个答案。

From what I've read, Opera does not support the onpaste event. You could use the DOMAtrrModified event, but this would fire even when scripts change the value of the input box so you have to be careful with it. Unfortunately, I'm not familiar with mutation events so I wouldn't like to mess this answer up by writing an example that I wouldn't be confident of.

这篇关于我怎么知道用户正在打字或粘贴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆