Drag and drop implementation -- compatible with mobile phone and pc

Drag and drop is a very popular user interface mode. The concept is simple: click an object, hold down the mouse button, move the mouse to another area, and then release the button to put the object here.
The basic concept of drag and drop is simple: create an absolutely positioned element that can be moved to with the mouse.

<body>
    <div style="">
        <div class="draggable" style="width:100px;height:100px;position:absolute;background:red">Mobile div</div>
        <div class="draggable" style="width:100px;height:100px;position:absolute;background:green;left:120px;">Mobile div</div>
    </div>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://apps.bdimg.com/libs/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    var DragDrop = function() {
        var dragging = null;
        var diffX = 0;
        var diffY = 0;

        function handleEvent(event) {
            event = event || window.event;
            var target = event.target;
            switch (event.type) {
                case "mousedown":
                    if (target.className.indexOf("draggable") > -1) {
                        dragging = target;
                        diffX = event.clientX - target.offsetLeft;
                        diffY = event.clientY - target.offsetTop;
                    }
                    break;

                case "mousemove":
                    if (dragging !== null) {
                        dragging.style.left = event.clientX - diffX + "px";
                        dragging.style.top = event.clientY - diffY + "px"
                    }
                    break;

                case "mouseup":
                    dragging = null;
                    break;
            }
        }

        //Common interface
        return {
            enable: function() {
                document.addEventListener("mousedown", handleEvent, false);
                document.addEventListener("mousemove", handleEvent, false);
                document.addEventListener("mouseup", handleEvent, false);
            },
            disable: function() {
                document.removeEventListener("mousedown", handleEvent, false);
                document.removeEventListener("mousemove", handleEvent, false);
                document.removeEventListener("mouseup", handleEvent, false)
            }
        }
    }
    DragDrop().enable();
    </script>
</body>

The drag and drop feature doesn't really work until you know when the drag starts. From this point of view, the preceding code does not provide any means to indicate that the drag is starting, dragging, or already finished. At this time, you can use custom events to indicate the occurrence of these events, and let other parts of the application interact with the drag function.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Drag and drop</title>
    <style type="text/css">
    .drap-container {
        padding-top: 15px;
    }

    #dragWrap {
        height: 100px;
        background: #f2f2f2;
        width: 300px;
        height: 300px;
        border: 1px solid #ccc;
        position: relative;
        float: left;
        margin-right: 20px;
        padding: 10px;
    }

    .draggable {
        width: 100px;
        height: 100px;
        position: absolute;
        color: #fff;
        text-align: center;
        padding: 10px;
        cursor: pointer;
    }

    .box1 {
        background: #5972f1;
    }

    .box2 {
        left: 120px;
        background: #47bf6c;
    }

    #status {
        height: 35px;
        line-height: 35px;
        background: #fdf5f0;
        padding: 0 15px;
        border: 1px solid #fde4d4;
        margin-bottom: 10px;
    }

    @media(max-width:500px) {
        #dragWrap {
            width: 100%;
            float: none;
        }
    }
    </style>
</head>

<body class="">
    <div class="container drap-container">
        <div id="dragWrap">
            <div class="draggable box1" id="box1">Mobile div</div>
            <div class="draggable box2" id="box2">Mobile div</div>
        </div>
        <div id="status">status</div>
    </div>
    <script type="text/javascript">
    function EventTarget() {
        this.handlers = {}
    }
    EventTarget.prototype = {
        constructor: EventTarget,
        addHandler: function(type, handler) {
            console.log(type);
            //At first, only type did not assign a value to this.handlers[type]
            if (typeof this.handlers[type] == "undefined") {
                this.handlers[type] = [];
                //console.log("hi")
            }
            //Then push
            this.handlers[type].push(handler);
            console.log(this.handlers[type]);

        },
        fire: function(event) {
            if (!event.target) {
                event.target = this;
                //console.log("not have eventTarget")
            }
            if (this.handlers[event.type] instanceof Array) {
                //console.log("isArray")
                var handlers = this.handlers[event.type];
                //Loop multiple events
                for (var i = 0, len = handlers.length; i < len; i++) {
                    handlers[i](event);
                }

            }
        }
    }
    var DragDrop = function() {

        var wrap = document.getElementById("dragWrap");
        var dragdrop = new EventTarget();
        var dragging = null;
        var diffX = 0;
        var diffY = 0;
        var startEvt, moveEvt, endEvt;
        if ("ontouchstart" in window) {
            startEvt = "touchstart";
            moveEvt = "touchmove";
            endEvt = "touchend"
        } else {
            startEvt = "mousedown";
            moveEvt = "mousemove";
            endEvt = "mouseup";
        }

        function handleEvent(event) {
            //Get events and objects
            event = event || window.event;

            var target = event.target;
            //Determine event type
            switch (event.type) {
                case startEvt:
                    if (target.className.indexOf("draggable") > -1) {
                        dragging = target;
                        console.log(event.clientX)
                        if (startEvt == "touchstart") {
                            console.log(event)
                            diffX = event.touches[0].clientX - target.offsetLeft;
                            diffY = event.touches[0].clientY - target.offsetTop;

                            dragdrop.fire({ type: "dragstart", target: dragging, x: event.touches[0].clientX, y: event.touches[0].clientY });
                            console.log(event.touches[0].clientX, event.touches[0].clientY)
                        } else {
                            diffX = event.clientX - target.offsetLeft;
                            diffY = event.clientY - target.offsetTop;
                            dragdrop.fire({ type: "dragstart", target: dragging, x: event.clientX, y: event.clientY });
                        }
                    }



                    break;

                case moveEvt:
                    if (dragging !== null) {
                        if (moveEvt == "touchmove") {

                            event.preventDefault();
                            console.log(event)
                            dragging.style.left = event.touches[0].clientX - diffX + "px";
                            dragging.style.top = event.touches[0].clientY - diffY + "px";
                            console.log(event.touches[0].clientX, event.touches[0].clientY)
                            dragdrop.fire({ type: "drag", target: dragging, x: event.touches[0].clientX, y: event.touches[0].clientY })
                        } else {
                            dragging.style.left = event.clientX - diffX + "px";
                            dragging.style.top = event.clientY - diffY + "px";
                            dragdrop.fire({ type: "drag", target: dragging, x: event.clientX, y: event.clientY })
                        }

                    }
                    break;

                case endEvt:
                    if (endEvt == "touchend") {
                        console.log(endEvt)
                        console.log(event)
                        dragdrop.fire({ type: "dragend", target: dragging, x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY })
                    } else {
                        dragdrop.fire({ type: "dragend", target: dragging, x: event.clientX, y: event.clientY })
                    }
                    dragging = null;
                    break;
            }
        }

        //Common interface
        dragdrop.enable = function() {
                wrap.addEventListener(startEvt, handleEvent, false);
                wrap.addEventListener(moveEvt, handleEvent, false);
                wrap.addEventListener(endEvt, handleEvent, false);
            },
            dragdrop.disable = function() {
                wrap.removeEventListener(startEvt, handleEvent, false);
                wrap.removeEventListener(moveEvt, handleEvent, false);
                wrap.removeEventListener(endEvt, handleEvent, false)
            }
        return dragdrop
    }();
    //It can be written.
    //DragDrop=DragDrop() 
    //Return EventTarget{disable: ƒ (), enable: ƒ (), handlers: {drag: [F], drag: [F], dragstart: [F]}}}
    //console.log(DragDrop)
    DragDrop.enable();
    DragDrop.addHandler("dragstart", function(event) {
        var status = document.getElementById("status");
        status.innerHTML = "Started dragging " + event.target.id
    });
    DragDrop.addHandler("drag", function(event) {
        var status = document.getElementById("status");
        status.innerHTML = "Dragged " + event.target.id + " to(" + event.x + "," + event.y + ")";
    });
    DragDrop.addHandler("dragend", function(event) {
        var status = document.getElementById("status");
        status.innerHTML = "Dragged " + event.target.id + " at(" + event.x + "," + event.y + ")";
    });
    </script>
</body>

</html>

Because the DragDrop object is a singleton that uses the module pattern, some changes need to be made to use the EventTarget type. First, create a new EventTarget object, then add the enable() and disable() methods, and finally return the object.

View drag and drop effects

Tags: Front-end Mobile JQuery Javascript IE

Posted on Sun, 01 Dec 2019 06:49:48 -0800 by codesters