粘贴事件以修改内容并将其返回到同一位置 [英] Paste event modify content and return it at the same place

查看:135
本文介绍了粘贴事件以修改内容并将其返回到同一位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个jsfiddle来尝试解释我正在尝试做什么

I have created this jsfiddle for try to explain what Im trying to do

http://jsfiddle.net/nonyck/tyyCN/

$('.autoresize').bind('paste', function(e) {
    e.preventDefault();
    var data = e.originalEvent.clipboardData.getData('text');
     if(data.match("http://.*?.(jpg|png|gif)")) {
       $('.autoresize').val($('.autoresize').val() + "<image src='" + data + "' >");
     } else { 
       $('.autoresize').val( $('.autoresize').val() + data);
     }
});

我想做的是获取粘贴事件,然后对其进行修改,然后将其准确返回到焦点所在的位置,此示例中的atm仅将内容返回到末尾.

What Im trying is to get the paste event, then modify it and return it back exactly where is the focus, atm this example just returns the content to the end.

因此,如果用户在第2行中,然后在其中粘贴一些内容,然后将修改后的内容放在此处,而不是在文档的末尾.

So if the user is in the line 2, and pastes some content there, put the modified content there, and not at the end of the document.

有没有办法在正确的地方返回值?

Is there a way to return the value at the right place ??

推荐答案

您可以使用jQuery确定文本区域内插入符号的位置,以确定用户要将文本粘贴到的位置: 文本区域中的光标位置(字符索引,不是x/y坐标)

You can get the caret position within the textarea using jQuery to determine where the user wants to paste the text: Cursor position in a textarea (character index, not x/y coordinates)

然后将数据插入该位置.查看更新的小提琴: http://jsfiddle.net/tyyCN/1/

Then insert your data into that position. See updated fiddle: http://jsfiddle.net/tyyCN/1/

if(data.match("http://.*?.(jpg|png|gif)")) {
         var caret = $(this).getCursorPosition();
         var insert = "<image src='" + data + "' >";
         var val = $('.autoresize').val();
       $('.autoresize').val(val.substring(0, caret) + insert + val.substring(caret, (val.length)));
     }

这篇关于粘贴事件以修改内容并将其返回到同一位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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