drag.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. $(document).on('mousedown', '.hgc_dialogContent h2', function(e) {
  2.   var drag = $(this).parent();
  3. //webkit内核和火狐禁止文字被选中
  4.   $('body').addClass('select');
  5. if ($(e.target).hasClass('layer-close')) { //点关闭按钮不能拖拽模态框
  6.   return;
  7. }
  8. //鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
  9.   var diffX = e.clientX - drag.offset().left;
  10.   var diffY = e.clientY - (drag.offset().top - $(window).scrollTop());
  11.   $(document).on('mousemove', function(e) {
  12.     e = e || window.event; //兼容ie浏览器
  13.     var left = e.clientX - diffX;
  14.     var top = e.clientY - diffY;
  15. console.log(e.clientY)
  16.     if (left < 0) {
  17.       left = 0;
  18.     } else if (left > window.innerWidth - drag.width()) {
  19.       left = window.innerWidth - drag.width();
  20.     }
  21.     if (top < 0) {
  22.       top = 0;
  23.     } else if (top > window.innerHeight - drag.height()){
  24.       top = window.innerHeight - drag.height();
  25.     }
  26.     //移动时重新得到物体的距离,解决拖动时出现晃动的现象
  27.     drag.css({
  28.       'left': left + 'px',
  29.       'top': top + 'px'
  30.     })
  31.   })
  32.   $(document).on('mouseup', function(e) { //当鼠标弹起来的时候不再移动
  33.     $(document).unbind("mousemove");
  34.     $(document).unbind("mouseup");
  35.   });
  36. return false
  37. });