search
HomeWeb Front-endJS TutorialExample of using js to implement div dragging effect (compatible with PC and mobile)

I wrote a simple p dragging effect some time ago. Unexpectedly, I needed a similar requirement for the project yesterday, so I just used it. However, I encountered a problem when using the mobile terminal. Dragging The three events used when moving: mousedown, mousemove, and mouseup have no effect on the mobile terminal. After all, there is no mouse on the mobile terminal. After checking the information, I found that the corresponding events on the mobile terminal are: touchstart, touchmove, and touchend events. Another thing to note is that the coordinates of the current mouse are obtained on the PC side: event.clientX and event.clientY, and the coordinate positions are obtained on the mobile side: event.touches[0].clientX and event.touches[0]. clientY.

Let’s talk about how to achieve this effect. Let’s take a look at the effect first:

PC side

Example of using js to implement div dragging effect (compatible with PC and mobile)

Mobile side

Example of using js to implement div dragging effect (compatible with PC and mobile)

Let’s first analyze a dragging process. Taking the PC as an example, first the mouse is pressed (mousedown event), then moved (mousemove event), and finally the mouse is released (mouseup event ), first we need to set a variable to record whether the mouse is pressed. When the mouse is pressed, we make a mark, and then we need to record the current coordinates of the mouse and the current offset of p. When the mouse starts to move, record the current coordinates of the mouse. Use the current coordinates of the mouse minus the coordinates when the mouse is pressed plus the offset of p when the mouse is pressed. This is the distance between the current p and the parent element. When the mouse When released, change the mark to indicate that the mouse has been released.

Let’s take a look at the code:

var flag = false;    //是否按下鼠标的标记
var cur = {       //记录鼠标按下时的坐标
  x:0,
  y:0
}
var nx,ny,dx,dy,x,y ;
//鼠标按下时的函数
function down(){
  flag = true;       //确认鼠标按下
  cur.x = event.clientX;  //记录当前鼠标的x坐标
  cur.y = event.clientY;  //记录当前鼠标的y坐标
  dx = p2.offsetLeft;  //记录p当时的左偏移量
  dy = p2.offsetTop;   //记录p的上偏移量
}
//鼠标移动时的函数
function move(){
  if(flag){            //如果是鼠标按下则继续执行
    nx = event.clientX - cur.x; //记录鼠标在x轴移动的数据
    ny = event.clientY - cur.y; //记录鼠标在y轴移动的数据
    x = dx+nx;          //p在x轴的偏移量加上鼠标在x轴移动的距离
    y = dy+ny;          //p在y轴的偏移量加上鼠标在y轴移动的距离
    p2.style.left = x+"px";
    p2.style.top = y +"px";
  }
}
//鼠标释放时候的函数
function end(){
  flag = false;          //鼠标释放
}



Then add the event to this p. Let’s look at another one on the mobile side. What needs to be done, first of all, the events are different. You only need to add touchatart, touchmove, and touchend on the mobile side. There is also a different time when the mobile side obtains coordinates: event.touches[0].clientX and event.touches[0 ].clientY, this is also very simple, just add judgment. If it is a PC, use event. If it is a mobile terminal, use event.touches:

var touch ;
if(event.touches){
  touch = event.touches[0];
}else {
  touch = event;
}



Another thing to note is that when dragging p on the mobile terminal, the mobile page will automatically produce a sliding effect, so you also need to add a function to the page in touchmove to prevent the default event.

The following is the entire code, which can be simulated for mobile testing under Chrome. Click here to view:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>适配移动端的拖动效果</title>
  <style>
    #p1{
      height: 1000px;
    }
    #p2{
      position: absolute;
      top:0;
      left:0;
      width: 100px;
      height: 100px;
      background: #bbbbbb;
    }
  </style>
</head>
<body>
<p id="p1">
  <p id="p2"></p>
</p>
<script>
  var flag = false;
  var cur = {
    x:0,
    y:0
  }
  var nx,ny,dx,dy,x,y ;
  function down(){
    flag = true;
    var touch ;
    if(event.touches){
      touch = event.touches[0];
    }else {
      touch = event;
    }
    cur.x = touch.clientX;
    cur.y = touch.clientY;
    dx = p2.offsetLeft;
    dy = p2.offsetTop;
  }
  function move(){
    if(flag){
      var touch ;
      if(event.touches){
        touch = event.touches[0];
      }else {
        touch = event;
      }
      nx = touch.clientX - cur.x;
      ny = touch.clientY - cur.y;
      x = dx+nx;
      y = dy+ny;
      p2.style.left = x+"px";
      p2.style.top = y +"px";
      //阻止页面的滑动默认事件
      document.addEventListener("touchmove",function(){
        event.preventDefault();
      },false);
    }
  }
  //鼠标释放时候的函数
  function end(){
    flag = false;
  }
  var p2 = document.getElementById("p2");
  p2.addEventListener("mousedown",function(){
    down();
  },false);
  p2.addEventListener("touchstart",function(){
    down();
  },false)
  p2.addEventListener("mousemove",function(){
    move();
  },false);
  p2.addEventListener("touchmove",function(){
    move();
  },false)
  document.body.addEventListener("mouseup",function(){
    end();
  },false);
  p2.addEventListener("touchend",function(){
    end();
  },false);
</script>
</body>
</html>


The above is the detailed content of Example of using js to implement div dragging effect (compatible with PC and mobile). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!