时间:2021-07-01 10:21:17 帮助过:6人阅读
利用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>
相关推荐:
简单实现JSP分页显示效果
如何实现JS中图片压缩方法
如何实现JS中精巧的自动柯里化功能
以上就是简单实现JS 拖动效果的详细内容,更多请关注Gxl网其它相关文章!