您好,欢迎访问一九零五行业门户网

实现JS拖动效果的简单方法

本文主要和大家分享实现js拖动效果的简单方法,利用css3的trnsform的移动属性来实现的,希望能帮助到大家。
代码如下
<!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>
相关推荐:
js 拖动效果实现代码 比较简单_javascript技巧
以上就是实现js拖动效果的简单方法的详细内容。
其它类似信息

推荐信息