<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>拖拽</title> <style> *{margin:0;padding:0;} #box{width:100px;height:100px;background-color: #f00;position:absolute;left:0;top:0;} </style></head><body> <div id="box"> </div><script>var box=document.getElementById("box");box.οnmοusedοwn=function(e){ //获取获取鼠标初始位置 var mouse_x=e.clientX; var mouse_y=e.clientY;
var box_x=box.offsetLeft; var box_y=box.offsetTop; document.οnmοusemοve=function(e){ var mouse_now_x=e.clientX; var mouse_noe_y=e.clientY; result_x=box_x+mouse_now_x-mouse_x; result_y=box_y+mouse_noe_y-mouse_y; if(result_x<0){ result_x=0; }else if(result_x>document.body.clientWidth-100){ result_x=document.body.clientWidth-100 } if(result_y<0){ result_y=0; } box.style.left=result_x+"px"; box.style.top=result_y+"px"; }}box.οnmοuseup=function(){ document.οnmοusemοve=null;}</script></body></html>
WEB前端学习交流群21 598399936
转载于:https://www.cnblogs.com/luludehuhuan/p/8137394.html
相关资源:JavaScript简单拖拽效果(1)