原生js实现网页顶部自动下拉/收缩广告效果
知识要点
1.实现原理:
通过递归改变div的高度值达到缓慢下拉的效果。
2.一共分为3个步骤我写了三个函数
第一个show()函数(下拉):初始值高度h<300的话h+5 反之return退出停止,调用setTimeout方法30毫秒执行一次+5
第二个hide()函数(收回):只是高度的判断不同高度h-5反之return退出停止,调用setTimeout方法30毫秒执行一次-5
第三个dd()函数(再次弹出):这里要注意的是第二次弹出的div是一个新的div把它的高度设置为0,实现原理与第一个函数一样,
并且一定要在第二个函数(收回)执行后再执行
完整代码
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>demo</title>
<style>
body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;}
h1,h2,h3,h4,h5,h6{font-size:100%;}
address,cite,dfn,em,var{font-style:normal;}
code,kbd,pre,samp{font-family:couriernew,courier,monospace;}
ul,ol{list-style:none;}
a{text-decoration:none;}
a:hover{text-decoration:none;}
sup{vertical-align:text-top;}
sub{vertical-align:text-bottom;}
legend{color:#000;}
fieldset,img{border:0;}
button,input,select,textarea{font-size:100%;}
table{border-collapse:collapse;border-spacing:0;}
.clear{clear:both;float:none;height:0;overflow:hidden;}
#container{width:600px;margin:0auto;}
p{line-height:28px;}
.hidden{background:#E6E6E6;text-align:center;height:auto;overflow:hidden;}
.show{background:#808080;text-align:center;height:0;overflow:hidden;}
</style>
</head>
<body>
<divid="container">
<divclass="hidden"id="hid"><p>广告图</p></div>
<divclass="show"id="sho"><p>哈哈哈哈改装成功</p></div>
</div>
<scripttype="text/javascript">
window.onload=functionaa(){
show();
setTimeout("hide()",3000);
}
varh=0;
varhid=document.getElementById("hid");
varsho=document.getElementById("sho");
functionshow(){
if(h<300){
h+=5;
hid.style.height=h+"px";
}else{
return;
}
setTimeout("show()",30);
}
functionhide(){
if(h>0){
h-=5;
hid.style.height=h+"px";
}else{
dd();
return;
}
setTimeout("hide()",30);
}
vara=0;
functiondd(){
if(a<60){
a+=1;
sho.style.height=a+"px";
}else{
return;
}
setTimeout("dd()",30);
}
</script>
</body>
</html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!