mousedown、mousemove和mouseup

1.onmousedown:鼠标按下事件
2.onmousemove:鼠标移动事件
3.onmouseup:鼠标抬起事件

重点:

1、一定要绝对定位,脱离文档流才可以移动。

2、绑定拖拽的元素,移动和鼠标松开后是对document的绑定,因为移动的是整个div。

3、点击:a= 获取当前鼠标坐标、b =div距浏览器距离、c = 鼠标在div内部距离=a-b。

  1. 移动:通过 a - c 建立鼠标与div的关系,防止鼠标超出div

基本思路

  1. 拖拽状态 = 0鼠标在元素上按下的时候{
  2. 拖拽状态 = 1
  3. 记录下鼠标的xy坐标
  4. 记录下元素的xy坐标
  5. }
  6. 鼠标在元素上移动的时候{
  7. 如果拖拽状态是0就什么也不做。
  8. 如果拖拽状态是1,那么
  9. 元素y = 现在鼠标y - 原来鼠标y + 原来元素y
  10. 元素x = 现在鼠标x - 原来鼠标x + 原来元素x
  11. }
  12. 鼠标在任何时候放开的时候{
  13. 拖拽状态 = 0
  14. }
  1. window.onload = function(){
  2. var drag = document.getElementById('drag');
  3. // //点击某物体时,用drag对象即可,move和up是全局区域,
  4. // 也就是整个文档通用,应该使用document对象而不是drag对象(否则,采用drag对象时物体只能往右方或下方移动)
  5. drag.onmousedown = function(event){
  6. var event = event || window.event; //兼容IE浏览器
  7. // 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
  8. var diffX = event.clientX - drag.offsetLeft;
  9. var diffY = event.clientY - drag.offsetTop;
  10. if(typeof drag.setCapture !== 'undefined'){
  11. drag.setCapture();
  12. }
  13. document.onmousemove = function(event){
  14. var event = event || window.event;
  15. var moveX = event.clientX - diffX;
  16. var moveY = event.clientY - diffY;
  17. if(moveX < 0){
  18. moveX = 0
  19. }else if(moveX > window.innerWidth - drag.offsetWidth){
  20. moveX = window.innerWidth - drag.offsetWidth
  21. }
  22. if(moveY < 0){
  23. moveY = 0
  24. }else if(moveY > window.innerHeight - drag.offsetHeight){
  25. moveY = window.innerHeight - drag.offsetHeight
  26. }
  27. drag.style.left = moveX + 'px';
  28. drag.style.top = moveY + 'px'
  29. }
  30. document.onmouseup = function(event){
  31. this.onmousemove = null;
  32. this.onmouseup = null;
  33. //修复低版本ie bug
  34. if(typeof drag.releaseCapture!='undefined'){
  35. drag.releaseCapture();
  36. }
  37. }
  38. }
  39. }