简体   繁体   English

将图片投放到Chrome中的游标中

[英]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. 在Firefox中,如果我将图像从桌面拖到一个可信的字段中,它将作为base64嵌入到HIGHLIGHTED光标位置。

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

Now in Chrome, the image is opened by the browser (pageload, try in same fiddle). 现在在Chrome中,图像由浏览器打开(页面加载,尝试同样的小提琴)。

Thanks to the HTML5 you can catch the drop event, and catch the image with it. 感谢HTML5,您可以捕获drop事件,并使用它捕获图像。 But if I stop browsers default behavior, I am stuck not knowing where the user wanted to drop it. 但是,如果我停止浏览器默认行为,我不知道用户想要删除它的位置。

Can you suggest a workaround? 你能建议一个解决方法吗?

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 : 我假设你有相对于视口的放置位置的坐标作为变量xy以及作为变量img的丢弃图像:

Demo: http://jsfiddle.net/KZqNj/ 演示: 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() . 这将适用于最近的WebKit,Opera和Mozilla浏览器,尽管只有Firefox具有document.caretPositionFromPoint()的实现。

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM