HTML5 drag & drop behaviour

前端 未结 3 1335
终归单人心
终归单人心 2021-02-13 15:12

I\'m making extensive use of the HTML5 native drag & drop, and it\'s almost entirely behaving itself, with one small exception.

I\'m trying to highlight my dropzones

3条回答
  •  梦如初夏
    2021-02-13 15:51

    I may be getting overly complex here but I would do something like this:

    var draggingFile = false;
    var event2;
    
    //elements with the class hotspots are OK
    var hotspots = $(".hotspots");
    
    //Handlers on the body for drag start & stop
    $("body").live("dragover", function(event){ draggingFile = true; event2 = event; });
    $("body").live("dragexit dragleave drop", function(event){ draggingFile = false; event2 = event; });
    
    //Function checks to see if file is being dragged over an OK hotspot regardless of other elements infront
    var isTargetOK = function(x, y){
        hotspots.each(function(i, el){
            el2 = $(el);
            var pos = el2.offset();
            if(x => pos.left && x <= pos.left+el2.width() && y => pos.top && y <= post.top+el2.height()){
                return true;
            }
        });
        return false;
    };
    
    //Mousemove handler on body
    $("body").mousemove(function(e){
        //if user is dragging a file
        if(draggingFile){
            //Check to see if this is an OK element with mouse X & Y
            if(isOKTarget(e.pageX, e.pageY)){
                //Light em' up!
                lightdz(event2);
            } else { /* Fade em' :( */ dimdz(event2); }
        } else {
            dimdz(); //Having no parematers means just makes sure hotspots are off
        }
    });
    

    BTW that's probably not going to work straight off the bat, so you'll have to tweak it a bit to work with your code.

提交回复
热议问题