组件-拖拽 发表于 2020-12-08 | 分类于 组件 | 字数统计: 481字 | 阅读时长 ≈ 2分 封装一个拖拽组件 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127(function () { let transform = getTransform(); function Drag(selector) { this.elem = typeof selector === 'object' ? selector : document.getElementById(selector); this.startX = 0; this.startY = 0; this.sourceX = 0; this.sourceY = 0; this.init() } Drag.prototype = { constructor: Drag, init: function () { this.setDrag() }, getStyle: function (property) { return document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(this .elem)[property] : this.elem.currentStyle[property] }, //获取当前元素位置 getPosition: function () { let pos = { x: 0, y: 0 }; if (transform) { let transformValue = this.getStyle(transform); if (transformValue === 'none') { this.elem[transform] = 'translate(0,0)' } else { let tmp = transformValue.match(/-?\d+/g); pos = { x: parseInt(tmp[4].trim()), y: parseInt(tmp[5].trim()) } } } else { if (this.getStyle('position') === 'static') { this.elem.position = 'relative' } else { let left = this.getStyle('left'); let top = this.getStyle('top') pos = { x: parseInt(left ? left : 0), y: parseInt(top ? top : 0) } } } return pos }, //设置当前元素位置 setPosition: function (pos) { if (transform) { this.elem.style[transform] = `translate(${pos.x}px,${pos.y}px)` } else { this.elem.style.left = pos.x + 'px'; this.elem.style.top = pos.y + 'px' } }, //绑定事件 setDrag: function () { const self = this; this.elem.addEventListener('mousedown', start, false); //点击元素记录开始位置 function start(event) { self.startX = event.pageX; self.startY = event.pageY; let curPos = self.getPosition(autumn); self.sourceX = curPos.x; self.sourceY = curPos.y; document.addEventListener('mousemove', move, false); document.addEventListener('mouseup', end, false) } //鼠标移动 function move(event) { //获取鼠标当前位置 let currentX = event.pageX; let currentY = event.pageY; //计算差值 let distanceX = currentX - self.startY; let distanceY = currentY - self.startY; self.setPosition({ x: (self.sourceX + distanceX).toFixed(), y: (self.sourceY + distanceY).toFixed() }) } function end() { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', end) } } } //私有方法,用来获取兼容transform function getTransform() { let transform = null, divStyle = document.createElement('div').style, _transforms = ['transform', 'webkitTransform', 'MozTransform', 'msTransform'], i = 0, len = _transforms.length; for (; i < len; i++) { if (_transforms[i] in divStyle) { return transform = _transforms[i] } } return transform } window.Drag = Drag; })() //扩展为一个jQuery插件 (function ($) { $.fn.extend({ canDrag: function () { new Drag(this[0]); return this } }) })(jQuery) $('.autumn').canDrag() -------------本文结束感谢阅读-------------