1. 程式人生 > >點擊div掉下和上升

點擊div掉下和上升

else margin 生成 inner ets 點擊 wid val i+1

技術分享圖片

HTML

<div id="box"></div>

CSS

*{
	margin: 0;
	padding: 0;
}
#box div{
	width: 50px;
	height: 50px;
	background: red;
	position: absolute;
	top: 10px;
}

JS

var oBox=document.getElementById("box");
var aDiv=oBox.getElementsByTagName("div");
var num=0;
var timer=null;
//生成div
for (var i=0;i<10;i++) {
	oBox.innerHTML+="<div style=‘left: "+(i+1)*60+"px;‘></div>"
}
//點擊div往下掉
var onOff=true;
document.onclick=function(){
	clearInterval(timer);
	var oTop=parseInt(getStyle(aDiv[aDiv.length-1],"top"));
	if(oTop==400){
			onOff=false;
	}else{
		onOff=true;
	}
	timer=setInterval(function(){
		if(onOff){
			moveTo(aDiv[num],"top",400,10);
		}else{
			moveTo(aDiv[num],"top",10,10);
		}
		num++;
		if(num>=aDiv.length){
			clearInterval(timer);
			num=0;
		}
	},1000)
}

function moveTo(obj,attr,target,dir,endFn){
	clearInterval(obj.timer);
	dir=parseInt(getStyle(obj,attr))<target?dir:-dir;
	obj.timer=setInterval(function(){
		var speed=parseInt(getStyle(obj,attr))+dir;
		if(speed>target&&dir>0||speed<target&&dir<0){
            speed=target;
        }
		obj.style[attr]=speed+"px";
		 //清除定時器
        if(speed==target){
            clearInterval(obj.timer);
            if(endFn){
                endFn();
            }
        }
	},30)
}
function getStyle(obj,attr){
	if(obj.currentStyle){
		return obj.currentStyle[attr];
	}else{
		return getComputedStyle(obj)[attr];
	}
}

  

點擊div掉下和上升