码迷,mamicode.com
首页 > Web开发 > 详细

JS完美拖拽

时间:2019-12-19 21:34:00      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:pad   oct   utf-8   pagex   select   use   move   abs   title   

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
      *{
        margin: 0;
        padding: 0;
      }
      #box{
        height: 100px;
        width: 100px;
        background:red;
        position: absolute;
        cursor:move;
      }
    </style>
  </head>
  <body>
    <div id="box">

    </div>
  </body>
</html>
<script>
  var oBox = document.querySelector("#box");

  oBox.onmousedown = function(evt){
    var e = evt || event;
    var offsetX = e.offsetX;
    var offsetY = e.offsetY;
    document.onmousemove = function(evt){
      var e = evt || event;
      var x = e.pageX - offsetX;
      var y = e.pageY - offsetY;
      if(x<0){
        x = 0;
      }
      var maxLeft = window.innerWidth - oBox.offsetWidth;

      if(x > maxLeft){
        x = maxLeft;
      }
      if(y<0){
        y = 0;
      }
      var maxTop = window.innerHeight - oBox.offsetHeight;
      if(y > maxTop){
        y = maxTop;
      }
      oBox.style.left = x + "px";
      oBox.style.top = y + "px";
    }
    document.onmouseup = function(){
      document.onmousemove = null;
    }
  }
</script>

JS完美拖拽

标签:pad   oct   utf-8   pagex   select   use   move   abs   title   

原文地址:https://www.cnblogs.com/fengzhi/p/12069970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!