js实现鼠标拖拽和原轨迹返回

<!DOCTYPE html>

<html>

<head>
	<meta charset="utf-8">
	<title>拖拽</title>
	<style type="text/css">
		html,
		body {
			overflow: hidden;
		}

		body,
		div,
		h2,
		p {
			margin: 0;
			padding: 0;
		}

		body {
			color: #fff;
			background: #000;
			font: 12px/2 Arial;
		}

		p {
			padding: 0 10px;
			margin-top: 10px;
		}

		span {
			color: #ff0;
			padding-left: 5px;
		}

		#box {
			position: absolute;
			width: 300px;
			height: 150px;
			background: #333;
			border: 2px solid #ccc;
			top: 50%;
			left: 50%;
			margin: -75px 0 0 -150px;
		}

		#box h2 {
			height: 25px;
			cursor: move;
			background: #222;
			border-bottom: 2px solid #ccc;
			text-align: right;
			padding: 0 10px;
		}

		#box h2 a {
			color: #fff;
			font: 12px/25px Arial;
			text-decoration: none;
			outline: none;
		}
	</style>
	<script type="text/javascript">


	</script>
</head>

<body>
	<div id="box" style="margin-left: 0px; margin-top: 0px; left: 533px; top: 231px;">
		<h2 id="tz"><a href="javascript:;" id="a1">点击回放拖动轨迹</a></h2>
		<p><strong>Drag:</strong><span>false</span></p>
		<p><strong>offsetTop:</strong><span>231</span></p>
		<p><strong>offsetLeft:</strong><span>533</span></p>
	</div>
</body>

</html>
<script src="../../../public.js"></script>
<script>
	var box = document.getElementById("box");
	var tz = document.getElementById("tz");
	var btn=document.getElementById("a1");
    var arr=[];//保存位置信息
	box.onmousedown = function (eve) {
		var ee = eve || event;
		var x = ee.offsetX;
		var y = ee.offsetY;
		var target = ee.target || ee.srcElement;
		if (target.nodeName === "H2") {
			document.onmousemove = function (eve) {
				//改变box的位置
				//值与移动时的鼠标所位置有关
				var e = eve || event;
				var l = e.pageX - x;
				var t = e.pageY - y;

				window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
				//解决移动鼠标过程中不小心选中文字后出现的bug。
				//边界处理
				//l最小为0 最大不能超过浏览器的宽-box的宽
				//window.innerWidth
				//window.innerHeight	
				var maxL = document.documentElement.clientWidth - 300;
				var maxT = document.documentElement.clientHeight - 150;
				l = l < 0 ? 0 : (l > maxL ? maxL : l);
				t = t < 0 ? 0 : (t > maxT ? maxT : t);

				box.style.left = l + "px";
				box.style.top = t + "px";

				arr.push([box.style.left,box.style.top]);//保存位置信息
			}
		}
	}
	document.onmouseup = function () {
		document.onmousemove = null;
	}
	
	btn.onclick=function(){
		var index=arr.length-1;//从后向前执行位置信息。
		var timer=setInterval(function(){
			box.style.left=arr[index][0];
			box.style.top=arr[index][1];
			index--;
			if(index<0){
				clearInterval(timer);
			}
		},10)
	}
</script>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值