JavaScript 面向对象的拖拽

一、body

<div id="box"></div>

二、css

<style>

#box {

  position: abaolute;

  top: 0;

  left: 0;

  width: 100px;

  height: 100px;

}

</style>

三、JavaScript

<script>

  class Drag{

    constructor(el) {

      this.el = el;

      el.startOffset = null;

      el.startPoint = null;

      let move = (e) => {

        this.move(e);

      }

      let end = (e)=>{

        document.removeEventListener('mousemove', move);

        document.removeEventListener('mouseup', end);

      }

      el.addEventListener('mousedown', (e)=>{

        this.start(e);

        document.addEventListener('mousemove', move);

        document.addEventListener('mouseup', end);

      })

    }

    start(e) {

      let {el} = this;

      this.startOffset = {

        x: el.offsetLeft,

        y: el.offsetTop

      }

      this.startPoint = {

        x: e.clientX,

        y: e.clientY

      }

    }

    move(e) {

      let {el, startOffset, startPoint} = this;

      let nowPoint = {

        x: e.clientX,

        y: e.clientY

      }

      let dis = {

        x: nowPoint.x - startPoint.x,

        y: nowPoint.y - startPoint.y

      }

      el.style.left = startOffset.x + dis.x + 'px';

      el.style.top =startOffset.y + dis.y + 'px';

    }

  }

  let box = document.querySelector('#box');

  let drag = new Drag(box);

</script>

 

posted @ 2019-05-23 18:03  史海莹  阅读(195)  评论(0编辑  收藏  举报