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

原生JS实现拖动方法

时间:2015-12-07 10:14:22      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

function Drop(id){
	var obj = document.getElementById(id),
		H = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
		W = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
		maxWidth = W - obj.offsetWidth,
		maxHeight = H - obj.offsetHeight;

	obj.onmousedown=function(event){
		var event = event || window.event,
			startX = event.clientX,
			startY = event.clientY,
			posX = obj.offsetLeft,
			posY = obj.offsetTop;

		document.onmousemove=function(event){
			var event = event || window.event,
			 	moveX = event.clientX,
			 	moveY = event.clientY,
 				resultX = moveX - (startX - posX),
				resultY = moveY - (startY - posY);

				if(resultX <= 0){
					resultX = 0;
				}
				if(resultX >= maxWidth){
					resultX = maxWidth;
				}
				if(resultY <=0){
					resultY = 0;
				}
				if(resultY >= maxHeight){
					resultY = maxHeight;
				}

			obj.style.left = resultX+‘px‘;
			obj.style.top = resultY +‘px‘;

		}
	}
	obj.onmouseup=function(){
		document.onmousemove = null;
	}
}

  

//调用方式:
Drop(‘box‘);

 

原生JS实现拖动方法

标签:

原文地址:http://www.cnblogs.com/HCJJ/p/5025179.html

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