【问题标题】:jQuery drag and drop image to textarea handle eventjQuery 将图像拖放到 textarea 处理事件
【发布时间】:2013-09-30 22:21:42
【问题描述】:

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

我发现我可以将事件附加到 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);

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

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

要处理您的区域(文本区域或 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); 
?>

希望它对某人有所帮助。

【讨论】:

    【解决方案2】:

    jQuery UI 的简单方法,查看:

    编辑:

    祝你好运! :-)

    【讨论】:

    • 不,这不是我要找的。我想从我的桌面拖动图像。
    • @flinth 好的,你没有提到它。请更新您的问题!
    • @flinth:看看我的编辑。看来这个问题是重复的。
    • 老实说,我不寻找拖放,有很多例子,我看看如何处理我的例子中的图像从桌面拖放到文本区域
    • @flinth:我猜,你必须先上传图片(拖动到 textarea 上),然后将其加载到你的 textarea 编辑器中。它是“HTML 5 拖放”、“HTML 5 上传”的组合,并在您的 textarea-editor 中显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多