Drag and Drop: How to get the URL of image being d

2019-03-12 20:05发布

I have this code:

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

FIDDLE

If you drop the <img> element it alerts the url of the image. So far so good.

My problem is that if you drop the <a> element it alerts the url of the href of <a> element. I want to alert the url of the <img> element inside the <a> like if you droped the image in the above example.

Is that possible?

I dont mind using Jquery or any other library. I just want to take the url of the image inside a <a> element.

The whole point is to drag images-links from other websites to mine and get the url of images.

To be more clear what i am trying to achieve try to drag my profile image just under this post and drop it to fiddle. It alerts http://stackoverflow.com/users/3074592/laaposto. I want http://i.stack.imgur.com/juvdV.jpg?s=32&g=1 to be alerted.

I want the solution to work on latest version of Chrome and Firefox.

7条回答
啃猪蹄的小仙女
2楼-- · 2019-03-12 20:42
<body>
<!--the mouse over and dragging class are defined on each item-->
<div id="root" style="margin:20px 0 0 10px;">
<div id="handle" style="float:left;margin:2px 0 0 10px; padding:5px; background-color:#FFCC00;">Drage Folder</div>
<div id="drop" style="float:left;margin:2px 0 0 110px; padding:5px; background-color:#CCCC00;">Drop Folder</div>
</div>
<img id="example" src="fold.jpg" style="position: relative" />
<script type="text/javascript">
Drag.init(document.getElementById("example"));
</script>

Create drag-drop.js file and add following code.

var Drag = {
    obj : null,

    init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
    {
            o.onmousedown     = Drag.start;

            o.hmode                                  = bSwapHorzRef ? false : true ;
            o.vmode                                  = bSwapVertRef ? false : true ;

            o.root = oRoot && oRoot != null ? oRoot : o ;

            if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
            if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
            if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
            if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

            o.minX     = typeof minX != 'undefined' ? minX : null;
            o.minY     = typeof minY != 'undefined' ? minY : null;
            o.maxX    = typeof maxX != 'undefined' ? maxX : null;
            o.maxY    = typeof maxY != 'undefined' ? maxY : null;

            o.xMapper = fXMapper ? fXMapper : null;
            o.yMapper = fYMapper ? fYMapper : null;

            o.root.onDragStart  = new Function();
            o.root.onDragEnd    = new Function();
            o.root.onDrag                          = new Function();
    },

    start : function(e)
    {
            var o = Drag.obj = this;
            e = Drag.fixE(e);
            var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
            var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
            o.root.onDragStart(x, y);

            o.lastMouseX          = e.clientX;
            o.lastMouseY          = e.clientY;

            if (o.hmode) {
                    if (o.minX != null)      o.minMouseX           = e.clientX - x + o.minX;
                    if (o.maxX != null)    o.maxMouseX         = o.minMouseX + o.maxX - o.minX;
            } else {
                    if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
                    if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
            }

            if (o.vmode) {
                    if (o.minY != null)     o.minMouseY          = e.clientY - y + o.minY;
                    if (o.maxY != null)    o.maxMouseY         = o.minMouseY + o.maxY - o.minY;
            } else {
                    if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
                    if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
            }

            document.onmousemove        = Drag.drag;
            document.onmouseup             = Drag.end;

            return false;
    },

    drag : function(e)
    {
            e = Drag.fixE(e);
            var o = Drag.obj;

            var ey      = e.clientY;
            var ex      = e.clientX;
            var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
            var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
            var nx, ny;

            if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
            if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
            if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
            if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

            nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
            ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

            if (o.xMapper)                         nx = o.xMapper(y)
            else if (o.yMapper)  ny = o.yMapper(x)

            Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
            Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
            Drag.obj.lastMouseX               = ex;
            Drag.obj.lastMouseY               = ey;

            Drag.obj.root.onDrag(nx, ny);
            return false;
    },

    end : function()
    {
            document.onmousemove = null;
            document.onmouseup   = null;
            Drag.obj.root.onDragEnd(       parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
                                                                    parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
            Drag.obj = null;
    },

    fixE : function(e)
    {
            if (typeof e == 'undefined') e = window.event;
            if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
            if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
            return e;
    }
};
查看更多
在下西门庆
3楼-- · 2019-03-12 20:47

Here you go: working example

function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = evt.dataTransfer.getData('text/html');
    var rex = /src="?([^"\s]+)"?\s*/;
    var url, res;
    url = rex.exec(imageUrl);
    alert(url[1]);
}

It works on Chrome and Firefox, but note that if you drag an image from Chrome to Firefox it doesn't work.

查看更多
Emotional °昔
4楼-- · 2019-03-12 20:51

I think that's working:

http://fiddle.jshell.net/4E92W/3/

Using jQuery. (I'm just using it to get the "src" attribute so i think you can do without it)

I replaced:

var imageUrl = evt.dataTransfer.getData('URL');

With:

var imageUrl = evt.dataTransfer.getData('text/html');

Oh, and I replace the alert with a console.log so you'll need to open it.

Edit: It's not working with Firefox.

Edit2 : This one seems to work with both browser : http://fiddle.jshell.net/4E92W/5/

查看更多
啃猪蹄的小仙女
5楼-- · 2019-03-12 20:54

This problem can be solved using only Javascript.

Piece of Code:

// onDrop
function onDrop(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    var imageUrl = evt.dataTransfer.getData("URL");
    var links = getAllElementsWith("a", "href", imageUrl);
    var image;
    // console.log(links, evt);

    if(links.length){
        image = links[0].getElementsByTagName("img");
        if(image.length)
            imageUrl = image[0].getAttribute("src");
        else
            imageUrl = "#no-image";
    }

    alert(imageUrl);
};

JSFiddle Here: http://jsfiddle.net/hayatbiralem/7pr7N/5/

Thanks to kevinfahy for getAllElementsWithAttribute function.

查看更多
时光不老,我们不散
6楼-- · 2019-03-12 20:57

Add an event listener to the window for the "drag" event. Set a global variable to the event source (I.E. The element in the page being dragged.) Then on "drop" you grab that the information you require from the element.

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

window.addEventListener('drag', handleClicks, false);

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

function handleClicks(evt){
    DragElement = evt.srcElement;
}

function noopHandler(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}
function drop(evt) {
    console.log(evt);
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = DragElement.src;
    alert(imageUrl);
}

http://fiddle.jshell.net/exx4e/

查看更多
该账号已被封号
7楼-- · 2019-03-12 21:05

Here's how I'd do it (only tested in Firefox):

  • use jQuery
  • analyze the dropped html-code using jQuery: search for image inside with .find()
  • read src-attribute from the found image with .attr()

Here's the important part from my new drop(event) function:

// Get text/html instead of text/uri-list!
// So you get raw html that is passed even between different websites
var droppedHTML = evt.dataTransfer.getData("text/html");

// add this html to some container.
// if you skip this, the following code won't work if a single img element is dropped
var dropContext = $('<div>').append(droppedHTML);

// now you can read the img-url (not link-url!!) like this:
var imgURL = $(dropContext).find("img").attr('src');

Here's the working JSFiddle: http://fiddle.jshell.net/4r7dT/1/

And yes: You can drag-drop your user-icon into that box and will get the img url. ;)

查看更多
登录 后发表回答