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 21:08

Here is my fiddle: http://fiddle.jshell.net/ep2z5/

This works in chrome on my Mac. Basically you take the html returned, and then convert into jquery object, and since the return string is a meta tag, and an img tag, you have to take the 2nd element (number 1 in the array returned by jquery parsing) and jquery-ify that item, and then grab the src attribute.

Update: checked firefox and it isn't working there, researching now.

Update: Okay here is the newest fiddle tested in both chrome and firefox. http://fiddle.jshell.net/ep2z5/6/

It uses recursion, which can be dangerous, but i think will work okay, as long as there isn't to many nested elements.

查看更多
登录 后发表回答