码迷,mamicode.com
首页 > Web开发 > 详细

JS 简单拖拽

时间:2015-01-05 16:11:53      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

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;      
}    

 

JS 简单拖拽

标签:

原文地址:http://www.cnblogs.com/lxdd/p/4203745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!