我有一个 contenteditable div,我希望用户能够将图像文件从他们的计算机拖放到 div 中。这在 FF 中按预期工作,但在 chrome 中,它不是将文件放入 div,而是离开页面并在浏览器中打开文件。我觉得我一定在这里遗漏了一些基本的东西,因为 facebook、gmail 等在 Chrome 中可以拖放文件。
我只是在用
<div contenteditable='true'></div>
这是一把 fiddle http://jsfiddle.net/Jt9LU/
如果我需要在 CSS、JS、jQuery 或 HTML 标记中添加任何内容,我们将不胜感激,因为它看起来确实很简单。
在 Chrome 34 和 Chrome Canary 36 中试用
最佳答案
非常感谢 RobM 为我指明了正确的方向。使用您提供的其他 SO 答案以及您提供的教程链接,这是一个在 FF 和 chrome 中为我工作的解决方案
(参见 fiddle :http://jsfiddle.net/MWe8U/)
HTML
Content Editable Div:
<div id='d' class='demo' contenteditable='true'>
</div>
CSS
.demo{
height:400px;
border:1px solid black;
overflow-y:scroll;
}
JS
$(document).ready(function() {
var handleDrag = function(e) {
//kill any default behavior
e.stopPropagation();
e.preventDefault();
};
var handleDrop = function(e) {
//kill any default behavior
e.stopPropagation();
e.preventDefault();
//console.log(e);
//get x and y coordinates of the dropped item
x = e.clientX;
y = e.clientY;
//drops are treated as multiple files. Only dealing with single files right now, so assume its the first object you're interested in
var file = e.dataTransfer.files[0];
//don't try to mess with non-image files
if (file.type.match('image.*')) {
//then we have an image,
//we have a file handle, need to read it with file reader!
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
//get the data uri
var dataURI = theFile.target.result;
//make a new image element with the dataURI as the source
var img = document.createElement("img");
img.src = dataURI;
//Insert the image at the carat
// Try the standards-based way first. This works in FF
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. This works in Chrome.
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
range.insertNode(img);
}
else
{
//not supporting IE right now.
console.log('could not find carat');
}
});
//this reads in the file, and the onload event triggers, which adds the image to the div at the carat
reader.readAsDataURL(file);
}
};
var dropZone = document.getElementById('d');
dropZone.addEventListener('dragover', handleDrag, false);
dropZone.addEventListener('drop', handleDrop, false);
});
关于javascript - 将图像文件拖放到 contenteditable div : works fine in FF, 在 Chrome 中失败得很惨,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23548745/