js实现拖拽功能

时间:2021-05-26

效果图:(红色方块可任意拖动)

代码如下:

<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> <div id="d1"></div> </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 ; }; } </script></html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章