SoFunction
Updated on 2025-03-10

JS implements simple drag and drop effect

This article has shared with you the specific code for implementing simple drag and drop effects of js for your reference. The specific content is as follows

1. The basic effect of dragging

Ideas:

When the mouse is pressed on the box, prepare to move (events are added to the object)

When the mouse moves, the box follows the mouse moves (events added to the page)

When the mouse is raised, the box stops moving (event added to the page)

var o = ('div');
 
        //Press the mouse         = function (e) {
            //The position of the mouse relative to the box            var offsetX =  - ;
            var offsetY =  - ;
            //Mouse Move             = function (e) {
                 =  - offsetX + "px";
                 =  - offsetY + "px";
            }
            //Release the mouse             = function () {
                 = null;
                 = null;
            }
        }

2. Drag and drop problem

If text appears in the box, or the box itself is an image, due to the browser's default behavior (text and image can be dragged and dropped), we can set return false to block its default behavior. However, this default behavior of interception is not applicable in the lower version of IE. Global capture can be used to solve the IE problem.

Global Capture

Global capture is only available for IE lower version browsers.

<button>btn1</button>
    <button>btn2</button>
    <script>
        var bts = ('button')
 
        bts[0].onclick = function () {
            (1);
        }
        bts[1].onclick = function () {
            (2);
        }
 
        // bts[0].setCapture() //Add global capture        // bts[0].releaseCapture() ;//Release global capture</script>

Once a global capture is added to the specified node, other elements in the page will not trigger events of the same type.

3. Full version of drag and drop

var o = ('div');
 
        //Press the mouse         = function (e) {
            if () {   //IE lower version                ()
            }
            e = e || 
            //The position of the mouse relative to the box            var offsetX =  - ;
            var offsetY =  - ;
            //Mouse Move             = function (e) {
                e = e || 
                 =  - offsetX + "px";
                 =  - offsetY + "px";
            }
            //Release the mouse             = function () {
                 = null;
                 = null;
                if () {
                    ();//Release global capture                }
            }
            return false;//The default behavior of standard browsers        }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.