jQuery将图像拖放到textarea句柄事件中

时间:2013-09-30 22:21:42

标签: javascript jquery html

我想创建一个文本区域来处理桌面上的图像丢弃事件。

我发现我可以将事件附加到html元素,但它无法正常工作。我没有发现任何错误,但它不起作用。 这是我的代码:

var imageDragOver = function imageDragOver(evt)
{
    console.log('imageDragOver');
    evt.stopPropagation();
    evt.preventDefault();
}

var imageDrop = function imageDrop(evt)
{
    console.log('imageDrop');
    evt.stopPropagation();
    evt.preventDefault();

}


document.addEventListener($('textarea'), imageDragOver, false);
document.addEventListener($('textarea'), imageDrop, false);

控制台日志中没有任何消息。我做错了什么?我不寻找已经制定的解决方案。

2 个答案:

答案 0 :(得分:4)

要处理您所在区域(文本区域或div)的放置事件,您需要执行以下操作:

var dropzone = document.getElementById('ta'); // paste your dropzone id here
dropzone.ondrop = function(e){
    console.log('drop'); // for debugging reasons
    e.preventDefault();  // stop default behaviour

    readfiles(e.dataTransfer.files); // function to handle file(s) that was added to dropzone
};

接下来,您需要将此文件发送到服务器并根据需要在浏览器中显示。

function readfiles(files) {
var formData = new FormData(); // we initialise a new form that will be send to php 

for (var i = 0; i < files.length; i++) {  // if we have more that one file
    previewImg(files[i]); // function to preview images

formData.append('file'+i, files[i]);

}

formData.append('moreInfo','myValuableValue');// you can append additional string info

$.ajax({
    url: './path_to_file_handler.php',
    type: 'POST',
    data: formData,
    async: true,
    success: function (data) {
        console.log(data);
    },
    cache: false,
    contentType: false,
    processData: false
 });


}       


function previewImg(file) {
var reader = new FileReader();

reader.onload = function (event) {

     var image = new Image();

    image.src = event.target.result; // set image source

    image.width = 550; // a fake resize


    document.getElementById('body').appendChild(image); // append image to body

};
reader.readAsDataURL(file);
}

测试path_to_file_handler.php的代码

<?php 
  print_r($_POST);
  print_r($_FILES); 
?>

希望它会对某人有所帮助。

答案 1 :(得分:2)

使用 jQuery UI 的简单方法,请查看:

修改

祝你好运! : - )