Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - Drop image into contenteditable in Chrome to the cursor

In Firefox, if I drag an image into a contenteditable field from the desktop, it will be embedded as base64 TO the HIGHLIGHTED cursor position.

JSFiddle: http://jsfiddle.net/zupa/YrwsS/

Now in Chrome, the image is opened by the browser (pageload, try in same fiddle).

Thanks to the HTML5 you can catch the drop event, and catch the image with it. But if I stop browsers default behavior, I am stuck not knowing where the user wanted to drop it.

Can you suggest a workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you can get the co-ordinates of the drop location (which I assume must be possible), you can do it as follows (untested). I'm assuming you've got the co-ordinates of the drop location relative to the viewport as variables x and y and the dropped image as the variable img:

Demo: http://jsfiddle.net/KZqNj/

Code:

var range;

// Try the standards-based way first
if (document.caretPositionFromPoint) {
    var pos = document.caretPositionFromPoint(x, y);
    range = document.createRange();
    range.setStart(pos.offsetNode, pos.offset);
    range.collapse();
    range.insertNode(img);
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
    range = document.caretRangeFromPoint(x, y);
    range.insertNode(img);
}
// Finally, the IE way
else if (document.body.createTextRange) {
    range = document.body.createTextRange();
    range.moveToPoint(x, y);
    var spanId = "temp_" + ("" + Math.random()).slice(2);
    range.pasteHTML('<span id="' + spanId + '">&nbsp;</span>');
    var span = document.getElementById(spanId);
    span.parentNode.replaceChild(img, span);
}

This will work in recent-ish WebKit, Opera and Mozilla browsers, although only Firefox has an implementation of document.caretPositionFromPoint().

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...