碰撞检测
代码
<!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> *{ margin:0; padding:0; } #box{ width:150px; height:150px; background:sandybrown; position: absolute; border:2px solid #ccc; } img{ width:100%; height:100%; } #center{ width:200px; height:160px; background:seagreen; position: absolute; left:50%; top:50%; margin-left:-100px; margin-top:-80px; } </style> </head> <body> <div id="box"><img src="images/1.jpeg" alt=""></div> <div id="center"></div> <script> /* 1.鼠标按下事件 onmousedown 2.鼠标移动事件 onmousemove 3.鼠标抬起事件 onmouseup */ var box = document.getElementById('box'); var center = document.getElementById('center'); // 鼠标按下 box.onmousedown = function(ev){ var eve = event || ev; var X = eve.clientX - box.offsetLeft; // 鼠标相对于box元素内部左边距 var Y = eve.clientY - box.offsetTop; // 鼠标相对于box元素内部上边距 // 鼠标移动 变成 页面移动 document.onmousemove = function(ev){ var eve = event || ev; box.style.left = eve.clientX - X + 'px'; // 移动时,鼠标相对于浏览器左侧左边距 - 鼠标相对于box元素内部左边距 = 移动时元素应该坐落的横坐标 box.style.top = eve.clientY - Y + 'px'; // 四周范围判断 if(eve.clientX - X <=0){ box.style.left = 0 + 'px'; } if(eve.clientY - Y <=0 ){ box.style.top = 0 + 'px'; } if(eve.clientX - X >= document.documentElement.clientWidth - box.offsetWidth){ box.style.left = document.documentElement.clientWidth - box.offsetWidth + 'px' ; } if(eve.clientY - Y >= document.documentElement.clientHeight - box.offsetHeight){ box.style.top = document.documentElement.clientHeight - box.offsetHeight + 'px' } // 碰撞检测 if(eve.clientX - X + box.offsetWidth >= center.offsetLeft && eve.clientY - Y + box.offsetHeight >= center.offsetTop && eve.clientX - X <= center.offsetLeft + center.offsetWidth && eve.clientY - Y <= center.offsetTop + center.offsetHeight ){ center.style.background = 'gray'; }else{ center.style.background = ''; } } // 鼠标抬起 document.onmouseup = function(){ // 移动、抬起事件置空 document.onmousemove = null; document.onmouseup = null; } return false; // 去除浏览器默认样式,如:文字选中,图片拖拽等 } </script> </body> </html>