欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript基础练习-拖拽练习

程序员文章站 2024-02-26 18:53:28
...

效果图如下(先拖拽,后回放):

javascript基础练习-拖拽练习

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
	  *{
	  		margin: 0;
            padding: 0;
        }
        #box{
    		width: 100px;
    		height:auto;
    		background:	rgba(255,165,0,0.6);
    		position:absolute;
            top: 100px;
            left: 500px;
            color: white;

        }
        #box .content{
        	width: 100%;
        	height: auto;
        	padding: 10px;
        }
        #box .drag{
        	cursor: move;
        	width: auto;
        	background: orange;
        	height: 30px;
        }
        #box .play{
        	background: orange;
        	width: auto;
        	height: 30px;
        	line-height: 30px;
        	text-align: center;
        	color: white;
        	cursor: pointer;
        }
	</style>
	<script type="text/javascript">
		window.onload=function(argument){
			var a=document.getElementById('box'),
				b=a.getElementsByTagName('div'),
				Drag,
				arr=[],
				X,
				Y;
			b[0].onmousedown=function(event){
				Drag=true;
				var event=event || window.event;
				X=event.clientX-a.offsetLeft;
				Y=event.clientY-a.offsetTop;
				//将包含方块坐标信息的对象推入数组
				arr.push({X:event.clientX-X,Y:event.clientY-Y});
			};
			document.onmousemove=function(event){
				if (Drag) {
					a.style.left=event.clientX-X+"px";
					a.style.top=event.clientY-Y+"px";
					b[1].innerHTML="left:"+a.offsetLeft+"<br/>"+"top:"+a.offsetTop;
					arr.push({X:event.clientX-X,Y:event.clientY-Y});
				}
			};
			document.onmouseup=function(){
				Drag=false;
			};
			//点击回放,通过setInterval函数每隔一段时间抛出数组中存放的包含坐标信息的对象
			b[2].onclick=function(){
				if(arr.length>1){
					var timer=setInterval(function(){
						var popArr=arr.pop();
						if (popArr) {
							a.style.left=popArr.X+"px";
							a.style.top=popArr.Y+"px";
							b[1].innerHTML="left:"+a.offsetLeft+"<br/>"+"top:"+a.offsetTop;
						}else{
							clearInterval(timer);
						}
					},30);
				}
			};
			b[1].innerHTML="left:"+a.offsetLeft+"<br/>"+"top:"+a.offsetTop;
		}
	</script>
</head>
<body>
	<div id="box">
		<div class="drag"></div>
		<div class="content"></div>
		<div class="play">回放</div>
	</div>
</body>
</html>