JS 简单拖拽

var login                   = document.getElementById(‘box‘);
login.onmousedown 	= function(e) {
			var e 	= getEvent(e);//获取event对象
			var _this 	= this;
			var diffX 	= e.clientX - _this.offsetLeft;//鼠标点击的坐标点x减去box元素距离左边的距离,得到的差为鼠标垫距离box元素左边的距离
			var diffY 	= e.clientY - _this.offsetTop;

			document.onmousemove 	= function(e) {
 //第一种方式,每次判断,然后给box元素的left赋值   
				if(e.clientX - diffX <= 0) {
					_this.style.left 	= ‘0px‘;
				}else if(e.clientX - diffX >= document.body.clientWidth - _this.offsetWidth) {
					_this.style.left 	= (document.body.clientWidth - _this.offsetWidth) + ‘px‘;
				}else {
					_this.style.left 	= (e.clientX - diffX) + ‘px‘;
				}
//这种方法更简洁,好看
				var top 				= e.clientY - diffY;
				if(top <= 0) 
					top 				= 0;
				else if(top >= document.body.clientHeight - _this.offsetHeight)
					top 				= document.body.clientHeight - _this.offsetHeight

				_this.style.top 	= top + ‘px‘;
				
			}
			document.onmouseup 		= function() {
//鼠标放开后,注销移动跟放开的事件
				this.onmousemove 		= null;
				this.onmouseup 		= null;
			}
		}        

function getEvent(event) {
   return event || window.event;      
}    

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。