接受拖拽从另一个浏览器窗口中删除图像 [英] Accept drag & drop of image from another browser window

查看:119
本文介绍了接受拖拽从另一个浏览器窗口中删除图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我知道如何设置拖动和放大器删除从用户计算机接受文件上载的目标。如何设置接受从其他网站拖动的图像的放置目标?我需要知道的是他们拖动的图片的网址。

In Javascript, I know how to set up a drag & drop target that accepts file uploads from the user's computer. How can I set up a drop target that accepts images that are dragged from another website? All I need to know is the URL of the image that they've dragged.

我知道这是可能的,因为Google文档接受来自其他网站的图片丢弃。知道他们是怎么做的吗?

I know this is possible, since Google Docs accepts image drops from other websites. Any idea how they're doing it?

推荐答案

你可以定义一个放置区:

You could define a drop zone:

<div id="dropbox">DropZone => you could drop any image from any page here</div>

然后处理 dragenter dragexit dragover drop 事件:

var dropbox = document.getElementById('dropbox');

dropbox.addEventListener('dragenter', noopHandler, false);
dropbox.addEventListener('dragexit', noopHandler, false);
dropbox.addEventListener('dragover', noopHandler, false);
dropbox.addEventListener('drop', drop, false);

function noopHandler(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}
function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = evt.dataTransfer.getData('Text');
    alert(imageUrl);
}


它位于下方我们正在将 dataTransfer 对象中的图像数据作为Text读取的事件处理程序。如果我们从其他网页中删除图像,则该文本将代表图像的网址。

​ It is inside the drop event handler that we are reading the image data from the dataTransfer object as Text. If we dropped an image from some other webpage this text will represent the url of the image.

这是一个 现场演示

更新:

看起来Chrome和Windows上的Chrome存在差异。在Windows dataTransfer.getData('Text'); 有效,但不适用于MacOS。 dataTransfer.getData('URL'); 应该适用于两者。

It looks like there are differences between Chrome on Windows and MacOS. On Windows dataTransfer.getData('Text'); works but not on MacOS. dataTransfer.getData('URL'); should work on both.

这篇关于接受拖拽从另一个浏览器窗口中删除图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆