js、jq拖拽效果封装实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a772116804/article/details/80330310
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>拖拽</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<style>
*{margin: 0;padding: 0;}
div{
  width: 100px;
  height: 100px;
  background: red;
  position: absolute;
  top: 0;
  left: 0;
}
</style>
</head>
<body>
<div id="div1"></div>
  <script type="text/javascript">
  //js写法
  var oDiv = document.getElementById('div1');
  drag(oDiv);
  function drag(obj){
      obj.onmousedown = function(event){
      var disX = event.clientX - this.offsetLeft;
      var disY = event.clientY - this.offsetTop;
      document.onmousemove = function(event){
        var L = event.clientX - disX ;
        var T = event.clientY - disY ;
        
        /*if(L < 0){ // L<80 为磁性吸附效果
          L = 0;
        }else if(L > document.documentElement.clientWidth - obj.offsetWidth){
          L = document.documentElement.clientWidth - obj.offsetWidth;
        }
        if(T < 0){ //if这开始为范围拖拽

          T = 0;
        }else if(T > document.documentElement.clientHeight - obj.offsetHeight){
          T = document.documentElement.clientHeight - obj.offsetHeight;
        }//*/

        obj.style.left = L + 'px';
        obj.style.top = T + 'px';
      }
      obj.onmouseup = function(){
        document.onmousemove= document.onmouseup = null;
      }
      return false;
    }
  } 
  //jq写法
    /*var disX = 0;
    var disY = 0;
    $('#div1').on('mousedown',function(ev){
      disX = ev.pageX- $(this).offset().left;
      disY = ev.pageY - $(this).offset().top;
   
    $(document).on('mousemove',function(ev){
      $('#div1').css('left',ev.pageX - disX);
      $('#div1').css('top',ev.pageY - disY);
    })
     $(document).on('mouseup',function(ev){
       $(this).off('mousedown');
       $(this).off('mousemove');
    });
     return false;
  });*/
  </script>
</body>
</html>

 

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页