我有一个令人满意的div,我希望用户能够将图像文件从他们的计算机中删除到div中。这在FF中可以正常工作,但在chrome中,不是将文件拖放到div中,而是导航离开页面并在浏览器中打开文件。我觉得我必须遗漏一些基本的东西,因为facebook,gmail等都有文件拖放功能在Chrome中运行。
我只是在使用
<div contenteditable='true'></div>
这是一个小提琴http://jsfiddle.net/Jt9LU/
我需要在CSS,JS,jQuery或HTML标记中添加任何内容,因为它看起来确实很简单。
尝试使用Chrome 34和Chrome Canary 36
答案 0 :(得分:9)
非常感谢RobM指出我正确的方向。使用您提供的其他SO答案以及您提供的教程链接,这是一个适用于FF和Chrome的解决方案
(见小提琴: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);
});