实现一个简单的拖拽

170 阅读1分钟

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .wrap{
      width: 600px;
      height: 600px;
      margin: 150px auto;
      border: 1px solid #000000;
      position: relative;
    }
    .drag{
      width: 50px;
      height: 50px;
      background: #DB0304;
      cursor: pointer;
      position: absolute;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <div class="drag"></div>
  </div>
</body>
<script src="./drag.js"></script>
</html>

JavaScript代码:

var dragDom = document.querySelector('.drag');
var wrap = document.querySelector('.wrap');

function drag(ele){
  var oldX, oldY, newX, newY;
  ele.onmousedown = function(e){
      this.style.position = 'relative';//元素相对定位
      if(!this.style.left && !this.style.top){//第一次设置left、top为0
        this.style.left = 0;
        this.style.top = 0;
      }
      oldX = e.clientX;//记录初始光标相对于视窗坐标
      oldY = e.clientY;
      document.onmousemove = function(e){
        newX = e.clientX;//获取当前新光标相对于视窗坐标
        newY = e.clientY;
        ele.style.left = parseInt(ele.style.left) + newX - oldX + 'px';//更新
        ele.style.top = parseInt(ele.style.top) + newY - oldY + 'px';
        oldX = newX;//新坐标变为老坐标
        oldY = newY;
      }
      document.onmouseup = function(){
        document.onmousemove = null;
        document.onmouseup = null;
      }
  }
}

drag(dragDom)

优化工作稍后再说,未完待续......