JavaScript to achieve simple drag effect

JavaScript to achieve simple drag effect

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

First look at the effect of the implementation:

Idea: Three events are used, mouse press, move, and release events

So first create the box and give it a CSS style

HTML:

//html
<div>
    <p>I am a blue box</p>
</div>

CSS:

CSS
*{margin: 0;padding: 0;}
        div{
            width: 100px;
            height: 100px;
            background-color: cornflowerblue;
            position: absolute;
        }
        p{
            width: 100px;
            height: 100px;
            line-height: 100px;
            font-size: 10px;
            color: #fff;
            text-align: center;
            transition: .5s all;
        }
        p:hover{
            transform: translateY(-5px);
            transition: .5s all;
            box-shadow: 10px 10px 5px gray;
}

Then set the corresponding method in JS

var div = document.querySelector('div');
        var p = document.querySelector('p');
        //First define and initialize variables x and y
        var x =0;
        var y = 0;
        // var i = 3;
        var TorF = false;
        //The text in the box cannot be selected div.onselectstart = function (e) {
            return false;
        }
        div.addEventListener('mousedown',function(e){
            // client: Output the coordinates of the mouse pointer when the mouse button is pressed x = e.clientX;
            y = e.clientY;
            // Format: obj.offsetLeft: Get the left and top offsets // Special note here: This property is read-only and cannot be assigned a value.
            // Returns the distance between the current element and the left side of the parent element (body). // Here, l and t do not declare a global variable, but create a property of a global object.
            l = div.offsetLeft;
            t = div.offsetTop;
            // Mouse settings move arrow div.style.cursor = 'move';
            p.innerHTML = 'I was pressed ^_^';
            TorF=true;
        });
        // When the entire screen triggers a move event document.addEventListener('mousemove',function(e){
            // If it is false, terminate the execution of the function and return the function value if (Torf == false) {
                return; 
            }
            // Define local variables in this function var twox = e.clientX;
            var twoy = e.clientY;
            // Use the obtained coordinates of the mouse pointer - (the coordinates of the mouse pointer - the offset) = the actual position of the mouse drag // The px unit must be added at the end, because the original acquisition has no unit var twol = twox - (xl);
            var twot = twoy - (yt); 
            div.style.left = twol+'px';
            div.style.top = twot+'px';
            p.innerHTML = 'I am being dragged-.-';
        });
        div.addEventListener('mouseup',function(){
            // Stop mouse movement events when releasing the keyboard TorF= false;
            // The mouse restores the default style div.style.cursor = 'default';
            p.innerHTML = 'I was bounced QAQ';
 })

Notice:

1. If you want to control the position of a box, you must add positioning to the box, otherwise the box will not move

2. The offsetLeft property is read-only and cannot be assigned a value.

3. Calculation of mouse position: mouse pointer coordinates - (mouse pointer coordinates - offset) = actual mouse drag position

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:
  • Common array operations in JavaScript
  • A simple and in-depth study of async and await in JavaScript
  • JavaScript implementation of classic snake game
  • Javascript basics about built-in objects
  • Detailed explanation of JavaScript operation mechanism and a brief discussion on Event Loop
  • Comparison between Python coroutines and JavaScript coroutines
  • JavaScript to achieve mouse tailing effect
  • Detailed explanation of JavaScript array deduplication
  • JavaScript to implement the aircraft war game
  • JavaScript setinterval delay one second solution
  • Detailed explanation of JavaScript upload file limit parameter case
  • A brief talk about JavaScript variable promotion
  • In-depth understanding of JavaScript event execution mechanism
  • 8 essential JavaScript code snippets for your project

<<:  Centos7 installation of MySQL8 tutorial

>>:  Solve the problem of VScode configuration remote debugging Linux program

Recommend

Detailed explanation of the basic usage of VUE watch listener

Table of contents 1. The following code is a simp...

How to use the dig/nslookup command to view DNS resolution steps

dig - DNS lookup utility When a domain name acces...

How to implement simple data monitoring with JS

Table of contents Overview first step Step 2 Why ...

React tsx generates random verification code

React tsx generates a random verification code fo...

Docker-compose one-click deployment of gitlab Chinese version method steps

1. Introduction to gitlab Gitlab official address...

Docker installation of Nginx problems and error analysis

question: The following error occurred when insta...

MYSQL master-slave replication knowledge points summary

An optimization solution when a single MYSQL serv...

Dynamically add tables in HTML_PowerNode Java Academy

Without further ado, I will post the code for you...

Pure js to achieve typewriter effect

This article example shares the specific code of ...

...

HTML is actually the application of learning several important tags

After the article "This Will Be a Revolution&...

Experience of redesigning the homepage of TOM.COM

<br />Without any warning, I saw news on cnB...

MySQL Learning: Three Paradigms for Beginners

Table of contents 1. Paradigm foundation 1.1 The ...

Thoughts on truncation of multi-line text with a "show more" button

I just happened to encounter this small requireme...