Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. ```
  2. <div class="box">1</div>
  3.  
  4. <div class="box">2</div>
  5.  
  6. var box = document.getElementsByClassName("box");
  7.  
  8. //鼠标按下
  9. box[0].onmousedown = function(e){
  10. //兼容IE
  11. var ev = e || window.event ;//window.event = event
  12.  
  13. var divX = ev.offsetX;
  14. var divY = ev.offsetY;
  15. //clientX:鼠标距离左边缘的距离
  16. //offsetX : 是鼠标在元素上的距离
  17. //var divX = ev.clientX - box.offsetLeft;
  18.  
  19. //在鼠标移动中(鼠标按住不动):计算元素距频幕左边缘的距离
  20.  
  21. document.onmousemove = function(e){
  22. var ev = e || event;
  23.  
  24. //元素距离屏幕左边缘的距离 = 鼠标距屏幕的距离 - 鼠标据元素左边缘的距离
  25. var x = ev.clientX - divX;
  26. var y = ev.clientY - divY;
  27.  
  28. //别忘了 去css样式里面加position:absolute;
  29. //上述所有功能都只是在计算数值,对页面没有任何影响
  30. //将数值拼接px 作为单位赋给元素的定位属性,才开始影响页面
  31.  
  32. box[0].style.left = x + "px";
  33.  
  34. box[0].style.top = y + "px";
  35.  
  36.  
  37.  
  38. //碰撞检测
  39. //获取移动视图上下左右的位置
  40. var moveL = box[0].offsetLeft;
  41. var moveR = box[0].offsetLeft + box[0].offsetWidth;
  42. var moveT = box[0].offsetTop;
  43. var moveB = box[0].offsetTop + box[0].offsetHeight;
  44.  
  45. //获取被撞视图的上下左右位置
  46. var hitL = box[1].offsetLeft;
  47. var hitR = box[1].offsetLeft + box[1].offsetWidth;
  48. var hitT = box[1].offsetTop;
  49. var hitB = box[1].offsetTop + box[1].offsetHeight;
  50.  
  51. //定义碰撞条件
  52. var r1 = moveR >= hitL;
  53. var r2 = moveL <= hitR;
  54. var r3 = moveT <= hitB;
  55. var r4 = moveB >= hitT;
  56.  
  57. if (r1 && r2 && r3 && r4) {
  58.  
  59.  
  60. document.onmousemove = null;
  61.  
  62. }
  63.  
  64. }
  65. //鼠标抬起时,置空移动事件,取消掉元素跟着鼠标移动的功能
  66.  
  67. document.onmouseup = function(){
  68.  
  69. document.onmousemove = null;
  70.  
  71. document.onmousedown = null;
  72. }
  73.  
  74. }
  75.  
  76.  
  77. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement