向动态创建的图像添加ondragstart处理程序 [英] adding ondragstart handler to dynamically created images

查看:30
本文介绍了向动态创建的图像添加ondragstart处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向动态创建的图像添加ondragstart处理程序:

  var image = new Image();image.src ="https://www.filepicker.io/api/file/JhJKMtnRDW9uLYcnkRKW";image.onload =函数(事件){this.ondragstart =拖动(事件);divImage.appendChild(this);};函数拖动(ev){ev.dataTransfer.setData("Text",ev.target.id);} 

但是,出现错误:未捕获的TypeError:无法调用未定义的方法'setData'

我已经尝试了通过dom加载的静态图片,并且效果很好,但是为什么我的动态生成的图片不能正常工作呢?由于某种原因,在拖动功能中,ev是动态创建的图像时,它不包含dataTransfer对象吗?有人知道为什么吗?

这就是我想要做的: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop除了,我希望能够通过javascript动态创建图像,并向其添加ondragstart处理程序.

谢谢

解决方案

由于动态生成的元素不属于页面加载时的DOM,因此您需要 addEventListener 到元素的每个新实例,例如这个:

  this.addEventListener('dragstart',function(){drag(ev)},false); 

我在此处创建了一个小提琴,向您展示了它的工作原理(对代码进行了一些修改,假设).

首先将img加载到蓝色的"body" div中,如果快速单击按钮两次,将看到此图像.

此Stackoverflow帖子与您的帖子密切相关: JavaScript ondrag,ondragstart,ondragend

如文章中所述,如果您想要跨浏览器的事件拖动解决方案,最好使用js框架.

I'm trying to add a ondragstart handler to my dynamically created image:

var image = new Image();
    image.src = "https://www.filepicker.io/api/file/JhJKMtnRDW9uLYcnkRKW";
    image.onload = function(event){
        this.ondragstart = drag(event);
        divImage.appendChild(this);
    };
function drag(ev)
    {
        ev.dataTransfer.setData("Text",ev.target.id);
    }

However, I get the error: Uncaught TypeError: Cannot call method 'setData' of undefined

I have tried this with a static image that I load via the dom and it works fine, but why doesn't my dynamically generated image work? For some reason, in the drag function, ev does not contain the dataTransfer object when it's a dynamically created image? Does anyone know why?

This is what I'm trying to do: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop except, I want to be able to dynamically create the image via javascript, and add the ondragstart handler to it.

Thanks,

解决方案

Because dynamically generated elements do not belong to the DOM on pageload, you need to addEventListener to every new instance of your element, like this:

this.addEventListener('dragstart', function() {drag(ev)}, false);

I created a fiddle here that shows you it works (with some modifications to your code and some assumptions).

The img's are first loaded into the blue 'body' div, you will see this if you click the button quickly a couple of times.

This Stackoverflow post is strongly related to yours: Javascript ondrag, ondragstart, ondragend

EDIT: As it's stated in the post, if you want a cross-browser solution for dragging events, you're better off using a js framework.

这篇关于向动态创建的图像添加ondragstart处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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