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>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章