JavaScript implements div mouse drag effect

JavaScript implements div mouse drag effect

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

Implementation principle: When the mouse is pressed, the mouse coordinate position is dynamically obtained according to the onmousemove event to update the position of the div. The premise of implementation is that the div must have a positioning effect, otherwise it cannot be moved.

HTML

<div class="box"></div>

CSS Styles

.box {
    position: absolute;
    width: 200px;
    height: 200px;
    background: red;    
    }

First, let's analyze the requirements. This requirement is that you can move and change the position of the div on the page only when the mouse is pressed when clicking. You can't move the mouse anymore if you release it. So there are three states of the mouse here, namely when the mouse is pressed (mousedown event), when it is moved (mousemove event), and when it is released (mouseup event)

So there are three events in the js part.

JS part

var box = document.getElementsByClassName("box")[0]; //Get the element var x, y; //Store the coordinates of div var isDrop = false; //Judge the moving state Press the mouse to move

When the mouse is pressed

box.onmousedown = function(e) {
                var e = e || window.event; //Use the event object to get the mouse position x = e.clientX - box.offsetLeft;
                y = e.clientY - box.offsetTop;
                isDrop = true; //Set to true to indicate that it can be moved}

e.clientX is the position of the mouse on the x-axis, e.clientY is the position of the mouse on the y-axis, box.offsetLeft gets the distance between the div and the left side, and box.offsetTop gets the distance between the div and the top side.

As shown in the figure below, e.clientX - box.offsetLeft we can get the deviation value between coordinate point x and box.offsetLeft. We need to subtract this deviation value from coordinate point x to get the actual distance the div has moved relative to the left. Similarly, e.clientY - box.offsetTop gets the distance offset from the top.

When the mouse moves

In order to prevent the mouse from moving too fast and the event cannot be handled correctly, the event is bound to the document.

document.onmousemove = function(e) {
         //Is it in movable state if(isDrop) {
                    var e = e || window.event;
              
                     var moveX = e.clientX - x; //Get the distance to the left var moveY = e.clientY - y; //Get the distance to the top box.style.left = moveX + "px";
                      box.style.top = moveY + "px";
          }else{
                       return ;
          }

            }

e.clientX - x mouse point coordinates minus the deviation get the distance from the div to the left, e.clientY - y mouse point coordinates minus the deviation get the distance from the div to the top. Reassign the left and top of div

When the mouse is released

In order to prevent the mouse from moving too fast and not being handled correctly, the event is bound to the document.

document.onmouseup = function() {
                isDrop = false; //Set to false to prevent movement}

Now the div can be dragged, but you need to add a range limit, otherwise the div will be dragged outside the page, which is not acceptable, so you need to add a range limit. The maximum mobile width of the div is the page width minus the div width, and the minimum is zero. The maximum height is the page height minus the div height, and the minimum is zero. So the scope should be written like this

document.onmousemove = function(e) {
      var e = e || window.event;
                if(is) {
                    var moveX = e.clientX - x;
                    var moveY = e.clientY - y;
                    var maxX = document.documentElement.clientWidth - box.offsetWidth; // Maximum distance that the X axis can move var maxY = document.documentElement.clientHeight - box.offsetHeight; // Maximum distance that the Y axis can move // ​​Range limit When the minimum is taken, the maximum is taken. When the maximum is taken, the minimum is taken if (moveX < 0) {
                        moveX=0
                     }else if(moveX>maxX){
                        moveX=maxX;
                    }
                    
                    if(moveY < 0) {
                        moveY=0;
                    }else if(moveY>maxY){
                        moveY=maxY; 
                    }

                    box.style.left = moveX + "px";
                    box.style.top = moveY + "px";

                } else {
                    return;
                }

            }

This effect is perfectly achieved, but we can also do it this way if the scope is limited.

The scope can be expressed as follows

//Range limit minimum to maximum maximum maximum to minimum if (moveX < 0) {
           moveX = Math.max(0,moveX) // 0
     }else if(moveX>maxX){
           moveX=Math.min(moveX,maxX);//maxX
     }
                    
      if(moveY < 0) {
          moveY = Math.max(0,moveY) //0
      }else if(moveY>maxY){
           moveY=Math.min(moveY,maxY); //maxY
      }

So we can write

moveX=Math.min(maxX, Math.max(0,moveX));
moveY=Math.min(maxY, Math.max(0,moveY));

Then the complete code

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .box {
                position: absolute;
                width: 200px;
                height: 200px;
                background: red;
            }
        </style>
    </head>

    <body>
        <div class="box"></div>
        <script>
            var box = document.getElementsByClassName("box")[0]; //Get the element var x, y; //The mouse is offset from the left and top of the div var isDrop = false; //Judge the moving state The mouse must be pressed to move box.onmousedown = function(e) {
                var e = e || window.event; //Use the event object to get the mouse position x = e.clientX - box.offsetLeft;
                y = e.clientY - box.offsetTop;
                isDrop = true; //Set to true to indicate it can be moved}

            document.onmousemove = function(e) {
                //Is it in movable state if(isDrop) { 
                       var e = e || window.event; 
                      var moveX = e.clientX - x; //Get the moving distance from the left var moveY = e.clientY - y; //Get the moving distance from the top //Maximum movable distance var maxX = document.documentElement.clientWidth - box.offsetWidth;
                    var maxY = document.documentElement.clientHeight - box.offsetHeight;

                    //Range limitation: when the moving distance is the smallest, take the maximum; when the moving distance is the largest, take the minimum //Range limitation method 1 /* if (moveX < 0) {
                        moveX = 0
                    } else if(moveX > maxX) {
                        moveX = maxX;
                    }

                    if(moveY < 0) {
                        moveY = 0;
                    } else if(moveY > maxY) {
                        moveY = maxY;
                    } */
                    //Range limitation method 2 moveX=Math.min(maxX, Math.max(0,moveX));
                    
                    moveY=Math.min(maxY, Math.max(0,moveY));
                    box.style.left = moveX + "px"; 
                     box.style.top = moveY + "px"; 
                         } else {
                    return; 
                         }

            }

            document.onmouseup = function() {
                isDrop = false; //Set to false to prevent movement}
        </script>
    </body>

</html>

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:
  • Using javascript to implement mouse drag events
  • JS implementation of moving sub-windows by dragging the mouse
  • js implements the method of switching pictures by dragging the mouse
  • js to achieve mouse drag multiple selection function example
  • JS mouse drag example analysis
  • jsMind adjusts the node position by dragging the mouse
  • js realizes the mouse dragging div to slide left and right
  • Detailed explanation of JavaScript mouse drag events
  • Super cool mouse drag page turning (paging) effect to achieve javascript code
  • js to achieve mouse drag and zoom div example code

<<:  Parameters to make iframe transparent

>>:  Docker nginx + https subdomain configuration detailed tutorial

Recommend

MySQL 5.7.24 installation and configuration graphic tutorial

This article shares the installation and configur...

Vue custom component implements two-way binding

Scenario: The interaction methods between parent ...

CSS pseudo-element::marker detailed explanation

This article will introduce an interesting pseudo...

Vue shopping cart case study

Table of contents 1. Shopping cart example 2. Cod...

Java example code to generate random characters

Sample code: import java.util.Random; import java...

JS, CSS style reference writing

CSS: 1. <link type="text/css" href=&q...

Tutorial on installing php5, uninstalling php, and installing php7 on centos

First, install PHP5 very simple yum install php T...

What to do if you forget the initial password of MySQL on MAC

The method to solve the problem of forgetting the...

Detailed explanation of how components communicate in React

1. What is We can split the communication between...

MySQL master-slave principle and configuration details

MySQL master-slave configuration and principle, f...

How to solve the problem of case insensitivity in MySQL queries

question Recently, when I was completing a practi...

HTML dl, dt, dd tags to create a table vs. Table creation table

Not only does it reduce the cost of website develo...

Implementing a simple web clock with JavaScript

Use JavaScript to implement a web page clock. The...