本文主要和大家分享实现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拖动效果的简单方法的详细内容。更多信息请关注PHP中文网其他相关文章!