简体   繁体   中英

HTML5 drag and drop not working correctly

I've made an example here:

http://jsfiddle.net/NQQL6/

When I start dragging a link, the cart should turn to green. When the item is dragged over the cart, the cart should become red.

This works, but only if the cart is empty :|

If there are any other elements in it, leave seems to be triggered when I drag the item over those elements. How can I prevent that from happening?

I've tried moving the event listener to the document element and check if event.target is a child or grandchild of cart but then leave seems to be triggered randomly on body even when the item is within the cart zone, so my class gets removed when it's not supposed to :(

Edit: found a few hacky solutions here: 'dragleave' of parent element fires when dragging over children elements

so you can delete this Q :)

You need to apply the following css to the list:

ul{ pointer-events: none; }

See this updated fiddle:

http://jsfiddle.net/NQQL6/1/

EDIT: Try this, http://jsfiddle.net/NQQL6/6/

Slightly more js logic, but it should work now.

A bit late to the game, you probably solved this, but you need to keep a reference counter to count the dragleave/dragenter events :

var counter = 0;

cart.addEventListener('dragenter', function(event){  
    counter++;
    cart.classList.add('ontop', 'activate');
    console.log('enter');
});

cart.addEventListener('dragleave', function(event){
  counter--;
  if (counter === 0) {
    cart.classList.remove('ontop');
  }
  console.log('leave');
});

See here

See also this this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM