原生JS实现网页顶部自动下拉与收缩广告效果

作者:白露

时间:2026-10-21

浏览:445

本文介绍如何使用原生JavaScript实现网页顶部自动下拉及收缩的广告效果。通过递归调用setTimeout控制div高度变化,分别编写show、hide和dd三个函数处理展开、收起及再次弹出的逻辑,无需依赖第三方库即可实现平滑的视觉交互。

文章目录

原生JS实现顶部广告自动展开与收起动画

知识要点

1.实现原理:

核心思路是通过递归方式动态修改div元素的高度数值,从而产生缓慢下拉的视觉动画效果。

2.一共分为3个步骤我写了三个函数

第一个show()函数(下拉):当初始高度h小于300时,执行h+5的操作;否则直接return退出停止。通过调用setTimeout方法,每30毫秒执行一次增加5像素的操作。

第二个hide()函数(收回):逻辑与show类似,但判断条件不同,当高度h大于0时执行h-5;否则return退出停止。同样调用setTimeout方法,每30毫秒执行一次减少5像素的操作。

第三个dd()函数(再次弹出):需要注意的是,第二次弹出的div是一个新的div实例,需将其高度初始设置为0。其实现原理与第一个函数一致,

并且一定要在第二个函数(收回)执行完毕后再执行。

完整代码


<!DOCTYPE html>
<html lang="en">
<head>
<meta http-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:courier new,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: 0 auto;}
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>
 <div id="container">
  <div class="hidden" id="hid"><p>广告图</p></div>
  <div class="show" id="sho"><p>哈哈哈哈改装成功</p></div>
 </div>
 <script type="text/javascript"> 
 window.onload=function aa(){
 show();
 setTimeout("hide()",3000);
 }
 var h=0;
 var hid=document.getElementById("hid");
 var sho=document.getElementById("sho");
 function show(){
 if(h<300){
  h+=5;
  hid.style.height=h+"px";
 }else{
  return;
 }
 setTimeout("show()",30);
 } 
 function hide(){
 if(h>0){
  h-=5;
  hid.style.height=h+"px";
 }else{
  dd();
  return;
 }
 setTimeout("hide()", 30);
 }
 var a=0;
 function dd(){
 if(a<60){
  a+=1;
  sho.style.height=a+"px";
 }else{
  return;
 }
 setTimeout("dd()",30);
 }
 </script>
</body> 
</html> 

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持本站!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章