js拖动效果
原理
主要思路是鼠标按下,鼠标按下并移动,鼠标松开。以上步骤对应的JS事件就是onmousedown,onmousemove,onmouseup。
实现代码
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();
修改
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); }; }; }