13.JavaScript实现鼠标左键拖拽效果
程序员文章站
2022-04-15 22:59:09
实现鼠标左键拖拽效果的两种方式: 方式一:
实现鼠标左键拖拽效果的两种方式:
方式一:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> <style> .move { width: 100px; height: 100px; background: red; border-radius: 50%; position:absolute; left:0; top:0; } </style> </head> <body> <div class="move"> </div> <script> //制作一个鼠标左键拖拽效果 var div = document.getelementsbyclassname("move")[0]; var style = window.getcomputedstyle(div); var divleft = parsefloat(style.left); var divtop = parsefloat(style.top); div.onmousedown = function(e){ if(e.button !== 0){ return ;//不是鼠标左键,return } window.onmousemove = function(e){ divleft += e.movementx;//距上次鼠标位置的x长度 divtop += e.movementy;//距上次鼠标位置的y长度 div.style.left = divleft + "px"; div.style.top = divtop + "px"; } window.onmouseup = window.onmouseleave = function(){ if(e.button === 0){//鼠标左键 window.onmousemove = null; } } } </script> </body> </html>
方式二:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title> <style> .move { width: 100px; height: 100px; background: red; border-radius: 50%; position:absolute; left:0; top:0; } </style> </head> <body> <div class="move"> </div> <script> //制作一个鼠标左键拖拽效果 var div = document.getelementsbyclassname("move")[0]; var style = window.getcomputedstyle(div); div.onmousedown = function(e){ if(e.button !== 0){ return ;//不是鼠标左键,return } var divleft = parsefloat(style.left); var divtop = parsefloat(style.top); var divpagex = e.pagex; var divpagey = e.pagey; window.onmousemove = function(e){ var disx = e.pagex - divpagex; var disy = e.pagey - divpagey; div.style.left = divleft + disx + "px"; div.style.top = divtop + disy + "px"; } window.onmouseup = window.onmouseleave = function(){ if(e.button === 0){//鼠标左键 window.onmousemove = null; } } } </script> </body> </html>
推荐阅读
-
求教,有这么一个效果,当把鼠标放上去二维码慢慢的出来,鼠标离开二维码慢慢的下去,怎么去实现。_html/css_WEB-ITnose
-
jQuery使用drag效果实现*拖拽div_jquery
-
javascript简单拖拽实现代码(鼠标事件 mousedown mousemove mouseup)_javascript技巧
-
js代码实现鼠标拖拽div实例
-
JavaScript实现的简单拖拽效果_javascript技巧
-
RecyclerView进阶:使用ItemTouchHelper实现拖拽和侧滑删除效果
-
WinForm实现鼠标拖动控件跟随效果
-
WPF 在image控件用鼠标拖拽出矩形的实现方法
-
Winform控件Picture实现图片拖拽显示效果
-
C#控件Picturebox实现鼠标拖拽功能