Paste event modify content and return it at the same place

纵然是瞬间 提交于 2019-12-24 15:14:46

问题


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);
     }
});

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.

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 ??


回答1:


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)

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)));
     }


来源:https://stackoverflow.com/questions/16813587/paste-event-modify-content-and-return-it-at-the-same-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!