JavaScript to achieve simple drag effect

JavaScript to achieve simple drag effect

This article shares the specific code of JavaScript to achieve the drag effect for your reference. The specific content is as follows

1.1 Basic effects of dragging

Ideas:

When the mouse is pressed on the box, it is ready to move (the event is added to the object)

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

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

var o = document.querySelector('div');
​
        //Mouse down o.onmousedown = function (e) {
            //Mouse position relative to the box var offsetX = e.clientX - o.offsetLeft;
            var offsetY = e.clientY - o.offsetTop;
            //Mouse movement document.onmousemove = function (e) {
                o.style.left = e.clientX - offsetX + "px";
                o.style.top = e.clientY - offsetY + "px";
            }
            //Mouse up document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
}

1.2 Drag and drop issues

If text appears in the box, or the box itself is an image, due to the default behavior of the browser (text and images can be dragged), it can be done by setting return false. However, intercepting the default behavior is not applicable in earlier versions of IE; you can use global capture to solve the IE problem.

1.2.1 Global capture

Global capture is only applicable to lower version IE browsers

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

Once a global capture is added for a specified node, other elements on the page will not trigger the same type of event

1.2.2 Full version of drag and drop

var o = document.querySelector('div');
​
        //Mouse down o.onmousedown = function (e) {
            if (o.setCapture) { //IE lower version o.setCapture()
            }
            e = e || window.event
            //Mouse position relative to the box var offsetX = e.clientX - o.offsetLeft;
            var offsetY = e.clientY - o.offsetTop;
            //Mouse movement document.onmousemove = function (e) {
                e = e || window.event
                o.style.left = e.clientX - offsetX + "px";
                o.style.top = e.clientY - offsetY + "px";
            }
            //Mouse up document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                if (o.releaseCapture) {
                    o.releaseCapture(); //Release global capture}
            }
            return false; //Default behavior of standard browsers}

1.3 Drag the border

Width of visible area:

Viewable area height:

//Screen height// var h=document.documentElement.clientHeight
// var w = document.documentElement.clientWidth;


// console.log(h,w);

analyze:

Maximum left: visible area width - box width

Minimum left: 0

Minimum top: 0

Maximum top: height of visible area - height of box

1.4 Collision

The key to collision is to find the critical value.

Name the four sides of the two objects: L1, T1, R1, B1 and L2, T2, R2, B2

If L1 > R2 || T1 > B2 || R1 < L2 || B1 < T2, then there is no collision.

<div class="one">
​
    </div>
    <div class="two"></div>
    <script>
        var o = document.querySelector('.one');
        var ox = document.querySelector('.two');
​
        //Mouse down o.onmousedown = function (e) {
            if (o.setCapture) { //IE lower version o.setCapture()
            }
            e = e || window.event
            //Mouse position relative to the box var offsetX = e.clientX - o.offsetLeft;
            var offsetY = e.clientY - o.offsetTop;
            //Calculate the maximum left and top margins (borders)
            var maxLeft = document.documentElement.clientWidth - this.offsetWidth;
            var maxTop = document.documentElement.clientHeight - this.offsetHeight;
            //Collision var L2 = ox.offsetLeft;
            var T2 = ox.offsetTop;
            var R2 = L2 + ox.offsetWidth;
            var B2 = T2 + ox.offsetHeight
            //Mouse movement document.onmousemove = function (e) {
                e = e || window.event
                var x = e.clientX - offsetX;
                var y = e.clientY - offsetY;
​
                //Calculate the boundary if (x <= 0) x = 0
                if (y <= 0) y = 0
                if (x >= maxLeft) x = maxLeft;
                if (y >= maxTop) y = maxTop;
​
                o.style.left = x + "px";
                o.style.top = y + "px";
                //Calculate collision var L1 = o.offsetLeft;
                var T1 = o.offsetTop;
                var R1 = L1 + o.offsetWidth;
                var B1 = T1 + o.offsetHeight;
                if (L1 > R2 || T1 > B2 || R1 < L2 || B1 < T2) { // No collision ox.style.backgroundColor = "blue"
                } else {
                    ox.style.backgroundColor = "orange"
                }
            }
            //Mouse up document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                if (o.releaseCapture) {
                    o.releaseCapture(); //Release global capture}
            }
            return false; //Default behavior of standard browsers}
​
</script>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JQuery Dialog (JS modal window, draggable DIV)
  • Analysis of how to use Sortable.js drag and drop sorting
  • js to achieve drag effect
  • JavaScript implements touch screen drag function on mobile terminal
  • Simple drag effect implemented using js
  • Example of file drag and drop upload function implemented by JS
  • Using javascript to implement mouse drag events
  • JavaScript implements horizontal progress bar drag effect
  • js perfect div drag example code
  • JS implements the touch screen drag function on mobile devices

<<:  MySql grouping and randomly getting one piece of data from each group

>>:  How to skip errors in mysql master-slave replication

Recommend

CSS modular solution

There are probably as many modular solutions for ...

React hooks pros and cons

Table of contents Preface advantage: shortcoming:...

Several common methods of CSS equal height layout

Equal height layout Refers to the layout of child...

MySQL backup table operation based on Java

The core is mysqldump and Runtime The operation i...

Solution to Nginx session loss problem

In the path of using nginx as a reverse proxy tom...

Web page experience: Web page color matching

<br />The color of a web page is one of the ...

How to implement Vue timer

This article example shares the specific code of ...

Detailed steps to build an independent mail server on Centos7.9

Table of contents Preface 1. Configure intranet D...

Notes on MySQL case sensitivity

Table of contents MySQL case sensitivity is contr...

JS realizes video barrage effect

Use ES6 modular development and observer mode to ...

Implementation of MySQL asc and desc data sorting

Data sorting asc, desc 1. Single field sorting or...

Analysis of the difference between Mysql InnoDB and MyISAM

MySQL supports many types of tables (i.e. storage...

Summary of commonly used escape characters in HTML

The commonly used escape characters in HTML are s...

MySQL 8.0.18 installation and configuration method graphic tutorial (linux)

This article records the installation and configu...