最近正在复习javascript,做的几个小案例觉得很不错,挺有意思的。
今天做了一个模仿163,,可以伸缩的页面。思路是定义两个div,分为上下两部分,上面的div的id=top下面的id=content,设置div样式,并让top的高度增加,增加到到一定的时候,停止增加。延迟几秒,把top部分进行收缩,当height=0时 停止收缩
代码中有详细的注释,上代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>仿163首页广告伸缩效果</title>
<style>
#top{
position:relative;
}
#content{
position:absolute;
}
</style>
</head>
<body onload="moveDown()">
<div id="top" style="width:100%; height:300px; background-color:#999"></div>
<div id="content" style="width:100%; height:500px; background-color:#FF9"></div>
</body>
</html>
<script language="javascript" type="text/javascript">
//定义一个步长(每次往下走多少)
var step=0;
var maxheight=200;
var t;
var top=document.getElementById("top");
//初始为隐藏状态
top.style.display="none";
//定义广告部分展开
function moveDown(){
//累加变量
step+=2;
//设置层高度等于累加值
top.style.height=step+"px";
//设置层显示
top.style.display="block";
if(step<=maxheight){
t = setTimeout("moveDown()",50);
}else{
clearTimeout(t);
setTimeout("moveUp()",3000);
}
}
//定义广告部分收缩
function moveUp(){
//累加变量
step-=2;
//设置层高度等于累加值
top.style.height=step+"px";
//设置层显示
top.style.display="block";
clearTimeout(t);
if(step<=0){
top.style.display="none";
}else{
//继续收缩
t=setTimeout("moveUp()",50);
}
}
</script>