<!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{ width: 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>