本文主要介紹了js實現拖曳效果的實例,具有很好的參考價值,下面跟著小編一起來看下吧
效果圖:(紅色方塊可任意拖曳)
#程式碼如下:
#<meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Document</title> <style type="text/css"> *{ margin:0; padding:0; } body{ background:url("img/2345_image_file_copy_1.jpg"); } #d1{ width:100px; height:100px; background:red; margin-left:300px; } </style> </head> <body> <p id="d1"></p> </body> <script> window.onload=function(){ var d1=document.getElementById("d1"); d1.onmousedown=function(e){ var mouseX=e.clientX; var mouseY=e.clientY;//计算xy var pianyiX=mouseX-d1.offsetLeft; var pianyiY=mouseY-d1.offsetTop; document.onmousemove=function(e){ var newX=e.clientX-pianyiX; var newY=e.clientY-pianyiY; d1.style.marginLeft=newX+"px"; d1.style.marginTop=newY+"px"; } }; document.onmouseup = function(e){ document.onmousemove = null ; }; } /* 结果,上面的onmousemove要写在document上,我写在p上导致错误 */ </script> </html>
更多js實作拖曳功能相關文章請關注PHP中文網!
#