将粘贴事件挂钩到隐藏的textarea [英] Hook paste event to hidden textarea

查看:181
本文介绍了将粘贴事件挂钩到隐藏的textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为< input type =text> 挂钩粘贴事件,并强制将此文本粘贴到隐藏的textarea中(然后我想解析textarea的发送文本并执行将数据从excel粘贴到gridview操作。类似于:

I want to hook paste event for <input type="text"> and force this text to be pasted into hidden textarea (then I want to parse textarea's text and perform 'paste data from excel to gridview' action). Something like:

$('#input1').bind('paste', function(e) {
    // code do paste text to textarea instead of originally targeted input
});

我应该编写哪些跨浏览器代码而不是评论?

What cross-browser code should I write instead of comments?

谢谢。

推荐答案

这个hacky解决方案可以激活焦点事件。 [是的,它不适用于contextmenu - > past]

There is this hacky solution that fires a focus event on a textarea when Ctrl and V keys or Shift and Insert keys are down. [Yes, it doesn't work for contextmenu -> past]

$(document).ready(function(){
    var activeOnPaste = null;
    $('#input1').keydown(function(e){
        var code = e.which || e.keyCode;
        if((e.ctrlKey && code == 86) || (e.shiftKey && code == 45)){
            activeOnPaste = $(this);
            $('#textarea').val('').focus();
        }
    });
    $('#textarea').keyup(function(){
        if(activeOnPaste != null){
            $(activeOnPaste).focus();
            activeOnPaste = null;
        }
    });
});

当Ctrl和V键关闭时,代码可以将指针聚焦在textarea上。在那一刻没有粘贴任何文本,它在此keydown函数被触发后被粘贴,因此粘贴的文本显示在textarea中。在那之后,在该textarea的keyup上,#input1 将被关注。

The code lets the pointer focus on a textarea when Ctrl and V keys are down. At that moment no text is pasted, it's pasted after this keydown function is fired so the pasted text is shown in the textarea. After that, on keyup on that textarea, #input1 will be focused.

键入此内容时,我发现使用范围可能有键盘粘贴和鼠标粘贴的解决方案。我也会尝试一下......

While typing this, I see that there may be a solution for both keyboard pasting and mouse pasting, using ranges. I'll try something with that too...

这篇关于将粘贴事件挂钩到隐藏的textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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