html:

<div style="position: absolute;width: 200px;height: 200px;border:1px solid #333">
  <div class="tag"style="height: 30px;border-bottom: 1px solid #333;"></div>
</div>

 

javascript:

依赖JQ

Drag('.tag');

function Drag(className){
  $(className).css({'cursor': 'all-scroll'})
  $(className).mousedown(function(e){
    var that = this;
// $(that).parent().css({'position': 'absolute'})
    var w = $(that).parent()[0].offsetLeft;
    var h = $(that).parent()[0].offsetTop;
    var w1 = e.screenX;
    var h1 = e.screenY;
    document.onmousemove = function(e1){
      var w2 = e1.screenX;
      var h2 = e1.screenY;
      var new_w = w + (w2 - w1);
      var new_h = h + (h2 - h1);
      new_w < 0 ? new_w = 0 : new_w;
      new_w > ($(document).width() - ($(that).parent().width() + 2)) ? new_w = $(document).width() - ($(that).parent().width() + 2) : new_w;
      new_h < 0 ? new_h = 0 : new_h;
      new_h > ($(document).height() - ($(that).parent().height() + 2)) ? new_h = $(document).height() - ($(that).parent().height() + 2) : new_h;
      $(that).parent().offset({left: new_w, top: new_h})
    }
  })
  $(className).mouseup(function(e){
    document.onmousemove = function(e1){
    }
  })
};

 

posted on 2018-06-29 16:16  YC小杨  阅读(115)  评论(0编辑  收藏  举报