JS drag effect
Principle
The main idea is to press the mouse, press and move the mouse, and release the mouse. The JS events corresponding to the preceding steps are onmousedown, onmousemove, and onmouseup.
Implementation Code
function dragElement(id) { this.dom = document.getElementById(id); this.isMouseDown = false; this.pos = null; } dragElement.prototype = { init: function() { var _this = this; this.dom.onmousedown = function(e) { _this.isMouseDown = true; _this.getPos(e); }; this.dom.onmouseup = function() { _this.isMouseDown = false; }; document.onmousemove = function(e) { _this.move(e); }; }, getPos: function(e) { e = e || window.event; this.pos = { x: e.clientX - this.dom.offsetLeft, y: e.clientY - this.dom.offsetTop }; }, move: function(e) { var _this = this; this.dom.style.opactiy if (this.isMouseDown) { this.dom.style.left = e.clientX - this.pos.x + "px"; this.dom.style.top = e.clientY - this.pos.y + "px"; } } } var d = new dragElement("m"); d.init();
Modify
init: function() { var _this = this; this.moveDom.onmousedown = function(e) { _this.isMouseDown = true; _this.getPos(e); document.onmouseup = function() { _this.isMouseDown = false; document.onmousemove = null; document.onmouseup = null; }; document.onmousemove = function(e) { _this.move(e); }; }; }