Home >Web Front-end >JS Tutorial >Simple implementation of JS drag effect
This article shares with you the code for simply realizing the JS drag effect, which is implemented using the mobile attribute of Trnsform of CSS3. Friends in need can take a look at the content of this article
Achieved by using the mobile attribute of CSS3 Trnsform.
The code is as follows
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #dom{ width: 50px; height: 50px; border: 2px solid red; } </style> </head> <body> <p id="dom"></p> <script> (function(){ let dom = document.getElementById('dom'); let moveX,moveY dom.addEventListener('mousedown',function (e) { moveX=e.target.offsetWidth; moveY=e.target.offsetHeight console.log(e); document.addEventListener('mousemove',move,false) }) function move(e){ if(moveY&& moveY){ let width =moveX/2,height = width+moveY; dom.style.transform='translate('+(e.x-width)+'px,'+(e.y-height)+'px)' } } document.addEventListener('mousemove',move,false) document.addEventListener('mouseup',function (e) { let width =moveX/2,height = width+moveY; let i =(e.x-width) +'px',y=(e.y-height)+'px'; if(moveX && moveY){ document.removeEventListener('mousemove',move,false); dom.style.transform='translate('+i+','+y+')'; moveY='',moveX='' } }) })() </script> </body> </html>
Related recommendations:
Simple implementation of JSP paging display effect
How to implement Image compression method in JS
How to implement the exquisite automatic currying function in JS
The above is the detailed content of Simple implementation of JS drag effect. For more information, please follow other related articles on the PHP Chinese website!