本文主要和大家分享實現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拖曳效果的簡單方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!