Javascript to achieve the drag effect of the login box

Javascript to achieve the drag effect of the login box

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

Demand Analysis

1. Click the pop-up login box

2. You can drag the login box to any position in the specific area of ​​the login box

3. You can close the login box, and the pop-up login box will return to its original position the next time you click it

Specific implementation

Complete code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        a {
            text-decoration: none;
            color: black;
        }
        .login-header {
           /* margin: 0 auto; */ /* width must be set for this to work*/
            height: 30px;
            line-height: 30px;
            font-size: 24px;
            text-align: center;
        }
        .login {
            width: 500px;
            height: 300px;
            position: absolute;
            border: #725252 solid 1px;
           /* transform: translate(-50%,-50%); */
            left: 50%;
            top: 50%;
            /* There can't be margin here, because we only changed the left and right, and after the move, the margin will take effect again, causing failure*/
           /* margin-left: -250px;
            margin-top: 50px; */
            background-color: seashell;
            transform: translate(-50%, -50%);
            z-index: 9999;
            box-shadow: 0 0 30px black;
            display: none;
            
        }
        .login-title {
            position: relative;
            margin: 20px 0 0 0;
            height: 40px;
            line-height: 40px;
            text-align: center;
            font-size: 20px;
            cursor: move;
        }
        .close-btn {
            position: absolute;
            width: 30px;
            height: 30px;
            right: -15px;
            top: -35px;
            border-radius: 50%;
            background-color: #ffffff;
            line-height: 30px;
        }
        .login-content{
            margin: 15px auto;
            width: 450px;
            height: 230px;
        }
        .login-input label{
            margin-top: 20px;
            margin-left: 30px;
            width: 100px;
            text-align: right;
            height: 30px;
            line-height: 30px;
            display: inline-block;
        }
        .login-input input {
            height: 30px;
            width: 230px;
            border-radius: 10px;
            border: 1px solid rgba(0, 0, 0, .5);
        }
        .login-btn {
            width: 100px;
            height: 50px;
            margin: 30px auto;
            border: 1px solid black;
            border-radius: 7px;
            line-height: 50px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="login-header"><a href="javascript:;" >Login pop-up login box</a></div>
    <div class="login">
        <div class="login-title">Login<span><a href="javascript:;" class="close-btn">x</a></span>
        </div>
        <div class="login-content">
                <div class="login-input">
                    <label for="name">Account:</label>
                    <input type="text" id="name">
                </div>
                <div class="login-input">
                    <label for="pwd">Login password:</label>
                    <input type="password" id="pwd">
                </div>
                <div class="login-btn">Login</div>
        </div>
    </div>
    <script>
        let out = document.querySelector('.login-header');
        let login_box = document.querySelector('.login');
        let title = document.querySelector('.login-title');
        let close = document.querySelector('.close-btn');
        let move = document.querySelector('.login-content');
        out.addEventListener('click',function() {
            login_box.style.display = 'block';
        });
        close.addEventListener('click',function () {
            login_box.style.left = 50 + '%';
                login_box.style.top = 50 + '%';
            login_box.style.display = 'none';
        });
        /* Only title can be moved*/
        title.addEventListener('mousedown',function(e) {
            /* Calculate the distance of the mouse in the title at the moment the mouse is pressed, and keep it unchanged until the next mouse press*/
            /* The offset of login_box must be used here, because there is an absolutely positioned login_box before title, and its offset is 0 */
            let mousex = e.pageX - login_box.offsetLeft;
            let mousey = e.pageY - login_box.offsetTop;
            console.log(mousex,mousey);
            /* Why is doucument used here instead of title? The reason is that the mouse may move too fast and exceed the scope of the title. Another reason is to prevent the title box from being blocked. If the mouse is not on the title, it cannot trigger the move and cancel event, so it cannot be invalidated.*/
            function movee(e) {
                login_box.style.left = e.pageX - mousex + 'px';
                login_box.style.top = e.pageY - mousey + 'px';
                
            }
            document.addEventListener('mousemove',movee)
            document.addEventListener('mouseup',function () {
                
                document.removeEventListener('mousemove',movee)
            })
        });
    
    </script>
</body>
</html>

How to implement the pop-up login box

Use JavaScript click event, and when the pop-up is clicked, set the display of the login box to unblock.

out.addEventListener('click',function() {
            login_box.style.display = 'block';
        });

Implementation of drag effect

The implementation of the drag effect is divided into three steps:

  • Mouse pressed, get the coordinates of the mouse in the login box
  • Move the mouse to get the position where the login box moves
  • Release the mouse to cancel the mouse movement event

1. Press the mouse to get the coordinates of the mouse in the login box

How to get the position of the mouse in the login box? Here we use the coordinates of the mouse in the page minus the left margin of the login box.

From the above figure, we can get that the coordinates of the mouse in the login box are: (x, y) = (page X − offsetLeft, Page Y − offsetTop) (x,y) = (pageX - offsetLeft, PageY - offsetTop) (x,y) = (pageX−offsetLeft, PageY−offsetTop)
Of course, the effect of the border on the offset is not considered here.

/* Calculate the distance of the mouse in the title at the moment the mouse is pressed, and keep it unchanged until the next mouse press*/
/* The offset of login_box must be used here, because there is an absolutely positioned login_box before title, and its offset is 0 */
let mousex = e.pageX - login_box.offsetLeft;
let mousey = e.pageY - login_box.offsetTop;

2. Move the mouse to get the location of the login box

At this time, the position of the mouse in the login box will not change until the mouse is released. We can use this feature to get the current position of the login box. That is, the coordinates of the mouse on the page minus the coordinates of the mouse on the page. I won’t go into further explanation here.

/* Why is doucument used here instead of title? The reason is that the mouse may move too fast and exceed the scope of the title. Another reason is to prevent the title box from being blocked. If the mouse is not on the title, it cannot trigger the move and cancel event, so it cannot be invalidated.*/
            function movee(e) {
                login_box.style.left = e.pageX - mousex + 'px';
                login_box.style.top = e.pageY - mousey + 'px';
                
            }
            document.addEventListener('mousemove',movee)

3. Release the mouse to cancel the mouse movement event

document.addEventListener('mouseup',function () {
                document.removeEventListener('mousemove',movee)
            })

Close the login box and return to the original position

Just set its display to none, see the code for details.

close.addEventListener('click',function () {
            login_box.style.left = 50 + '%';
            login_box.style.top = 50 + '%';
            login_box.style.display = 'none';
        });

Effect display

Difficulties encountered when implementing the code

1. When using margin to center, you must have width . I haven't written code for a long time and I have forgotten it.
2. Because I set margin for the login box, it moves out of position. This is because my coordinate calculation formula does not take margin into account (it only considers the left and right of the positioning). As a result, the login box reaches the coordinate position and then adjusts its position again because of magin . The solution should be to subtract margin when calculating the coordinates of the movement.
3. Offset is relative to the positioned parent node, so keep it in mind.
4. Why is the mouse movement an event bound to the document?

In order to prevent the mouse from moving too fast and not being handled correctly, the event is bound to the document. If the login box is not absolutely positioned, it may be blocked by other elements during the movement process, so the move event cannot be bound to the login box, but to the document.

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:
  • js realizes the mouse drag effect of the login box
  • js realizes the mouse drag effect of Baidu login box
  • Native JS to achieve draggable login box

<<:  How to fix the four sides of the table to scroll up, down, left and right

>>:  Nginx implements https website configuration code example

Recommend

An elegant way to handle WeChat applet authorization login

Preface When the WeChat mini program project invo...

Install Docker on Linux (very simple installation method)

I have been quite free recently. I have been doin...

Common writing examples for MySQL and Oracle batch insert SQL

Table of contents For example: General writing: S...

Vue code highlighting plug-in comprehensive comparison and evaluation

Table of contents Comprehensive comparison From t...

Installation process of CentOS8 Linux 8.0.1905 (illustration)

As of now, the latest version of CentOS is CentOS...

Solution to the data asymmetry problem between MySQL and Elasticsearch

Solution to the data asymmetry problem between My...

Steps to install Pyenv under Deepin

Preface In the past, I always switched Python ver...

How to use the realip module in Nginx basic learning

Preface There are two types of nginx modules, off...

Vue implements sample code to disable browser from remembering password function

Find information Some methods found on the Intern...

MySQL join buffer principle

Table of contents 1. MySQL join buffer 2. JoinBuf...

Examples of clearfix and clear

This article mainly explains how to use clearfix a...