html ondrop未触发,为什么ondrop html事件没有被解雇? - javascript代码 - 源码查

问题

I am trying to make a item system for my game, which will allow players to move items between slots by dragging and dropping them. As my test, I made a basic system with an item that can be dragged and then should, if dropped over the slot (black square), appear inside of it. However, it appears my ondrop event isn't firing.

I tried commenting out my normal code and put in just a console.log(), but it doesn't log anything which leaves me to believe that the event isn't firing.

HTML:

flint.png

JS:

function allowDrop(ev) {

ev.preventDefault();

}

function drag(ev) {

ev.dataTransfer.setData("img", ev.target.src);

}

function drop(ev) {

ev.preventDefault();

console.log('dropped!');

// (code to change image)

// var data = ev.dataTransfer.getData("img");

// ev.target.children[0].src = data;

}

I expected for the console to log 'dropped!', but it didn't. Can anyone help me? keep in mind that I am relatively new to Javascript and completely new to drag and drop and such.

Thank You!

解决方法

So from what I gathered from the MDN, event listeners will work when you label a element as dragable so we can just add event listeners for the dragover and drop events and then it will trigger. Further you can use conditionals to determine the target was correctly chosen and then trigger a function based on that.

They give a really good example that does exactly what you want. I would put the example in a code snippet and play around with it. I'm sure you'll understand it in no time.

document.addEventListener("dragover", function( event ) {

// prevent default to allow drop

event.preventDefault();

}, false);

function drag(ev) {

ev.dataTransfer.setData("img", ev.target.src);

}

document.addEventListener("drop", function( event ) {

console.log("dropped")

})

.slot{

width:50px;

height:50px;

background:black;

}

flint.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值