Catch image dragged into a text field in Javascript

有些话、适合烂在心里 提交于 2019-12-12 16:04:26

问题


I want to allow a user to drag an image from a web page into my web app and then store and use the image url elsewhere in the application. So I'm creating an input field as the drag target.

But since that allows to drop any draggable web object (like links), I need to do some error checking. I could put a button there, but it would be nicer if the drop is auto-detected.

So the question is... are there any event handlers - primarily supported in IE7 and Firefox3 - that get triggered when the image is dropped? Does it simply trigger a change event on the field?


回答1:


No, to my knowledge, there are no events that'll fire as soon as you make the drop.

Here's a possible solution:

var input = document.getElementById("input");
var lastVal = input.value;

setInterval(function() {
  if (input.value !== lastVal) {
    if (input.value) {
      if ( /\.(jpe?g|gif|bmp|png)(\?.*)?$/.test(input.value) ){
        alert('It\'s an image URL!!!');
      } else {
        alert('Not an image URL...');
      }
    }
    lastVal = input.value;
  }
}, 100);

Demo here: http://jsbin.com/izake

Note: It appears that some browsers (IE) don't let you drop items into fields like other browsers. It may be worth creating one from scratch - where everything on the page is draggable...




回答2:


You won't get an standard event directly after drag-and-drop (only after clicking outside the textfield), but perhaps you can use some kind of DragListener...

To check if the URL is a valid image, it will be best to check the extension (JPG, PNG, GIF...) and to check if the URL begins with "file:" - if it does, it links to a local image file and you should ignore it.



来源:https://stackoverflow.com/questions/1021171/catch-image-dragged-into-a-text-field-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!