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

MySQL 5.7 mysql command line client usage command details

MySQL 5.7 MySQL command line client using command...

How to customize at and cron scheduled tasks in Linux

There are two types of scheduled tasks in Linux s...

HTTP and HTTP Collaboration Web Server Access Flow Diagram

A web server can build multiple web sites with in...

CSS realizes the scene analysis of semi-transparent border and multiple border

Scenario 1: To achieve a semi-transparent border:...

Screen command and usage in Linux

Screen Introduction Screen is a free software dev...

Detailed explanation of asynchronous iterators in nodejs

Table of contents Preface What are asynchronous i...

How to set up Spring Boot using Docker layered packaging

The Spring Boot project uses docker containers, j...

Control the light switch with js

Use js to control the light switch for your refer...

MySQL database deletes duplicate data and only retains one method instance

1. Problem introduction Assume a scenario where a...

js to realize payment countdown and return to the home page

Payment countdown to return to the home page case...

Summary of various uses of JSON.stringify

Preface Anyone who has used json should know that...

Implementation of Node connection to MySQL query transaction processing

Table of contents Enter the topic mysql add, dele...

How to remotely connect to MySQL database with Navicat Premium

The party that creates a new connection is equiva...