<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #rect{ 200px; height: 200px; background: burlywood; position: absolute; left: 0; right: 0; } </style> </head> <body> <div id="rect"></div> </body> <script> // 面条代码 【容易想到】【不易扩展】 /*var rect = document.getElementById('rect'); var position; var isDrag = false; rect.onmousedown = function (e) { position = [e.offsetX, e.offsetY]; isDrag = !isDrag; document.onmousemove = function (e) { if (isDrag) { rect.style.left = e.clientX - position[0] + 'px'; rect.style.top = e.clientY - position[1] + 'px'; } } }; rect.onmouseup = function () { isDrag = !isDrag; }*/ // 构造函数写法 构造对象 // 抽象化 // var drag = { // el: '', // isDrag: false, // originX: 12, // originY: 30 // }; // drag.__proto__ = { // initOriginPos: function () {}, // changeDragStatus: function () {}, // bindEvent: function () {}, // horizontalMove: function () {}, // veticalMove: function () {}, // move: function () {}, // }; function Drag (el) { this.$el = typeof el === 'object' ? el : document.querySelector(el);//判断传入元素,判断是否已经获取,获取后为一个对象 this.$isDrag = false;//是否拖动,默认不拖动 this.$originX = undefined;//初始x值,鼠标按压后即获取 this.$originY = undefined;//初始y值,同上 this.$currentX = undefined;//鼠标移动后,当前x值 this.$currentY = undefined;//鼠标移动后,当前y值 this.bindEvent(this.$el, 'mousedown', this.initOriginPos);//鼠标点击绑定事件,执行函数 this.bindEvent(document, 'mousemove', this.move);//鼠标移动绑定事件,执行函数 this.bindEvent(this.$el, 'mouseup', this.changeDragStatus);//鼠标移出绑定事件,执行函数 } //以下为原型方法 Drag.prototype = { initOriginPos: function (event) { this.changeDragStatus(); var ev = event || window.event;//兼容IE浏览器,后者为ie9以下浏览器获取event方式 this.$originX = event.offsetX; this.$originY = event.offsetY; },//,从为拖动状态转换为拖动状态,点击时即获取偏移值,通过event属性获取,然后赋值给初始x,y值。 changeDragStatus: function () { this.$isDrag = !this.$isDrag; }, bindEvent: function (ele, type, handle) { ele.addEventListener(type, handle.bind(this)); }, horizontalMove: function () { this.$el.style.left = this.$currentX - this.$originX + 'px'; }, verticalMove: function () { this.$el.style.top = this.$currentY - this.$originY + 'px'; }, move: function (event) { if (this.$isDrag) { this.$currentX = event.clientX; this.$currentY = event.clientY; this.horizontalMove(); this.verticalMove(); } }, }; var drag=new Drag("#rect") </script> </html>