问题
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