js特效之定时展开、收缩广告的代码

发布时间:2020-06-24编辑:脚本学堂
本文介绍下,用js实现的定时展开与收缩广告的一段代码,有需要的朋友参考下。

定时展开与收缩广告的代码,如下:

<script>
/**
基本功能:
1、JS卷帘门广告特效,定时展开收缩广告,广告显示一定时间后自动关闭。
2、可设置显示时长,延迟时长,收展速度等参数。
3、可自定义广告展开前执行操作和广告收缩完成后执行操作。

使用示例:
var s = new slider('slideAd',3,1,10,90,3);
s.addafter(function(){alert("谢谢观看!");});

参数说明:
new slider(id, stay, delay, scrolldelay, MaxHeight, MinHeight);
id   'slideAd' 容器ID      (必选)
stay   [3]  显示时长      (可选,默认:3秒)
delay   [1]  延时,推迟展开     (可选,默认:1秒)
scrolldelay  [10]  停顿时间,值越小,收展速度越快   (可选,默认:10)

MaxHeight  [90]  容器最大高度,当广告展开到MaxHeight高度时停止展开 (可选,默认将容器完全展开)
MinHeight  [3]  容器最小高度,当广告收起到MinHeight高度时停止收起 (可选,默认:容器指定的height或0)

辅助功能:
addbefore - 添加广告展开前需要执行的操作,要求所传参数是function
addafter - 添加广告收缩完成后所需执行的操作,要求所传参数是function

//编辑整理:www.jb200.com
*/
function slider(id, stay, delay, scrolldelay)
{
 this.ID = document.getElementById(id);
 this.stay = typeof stay == "number" ? stay : 3;
 this.delay = typeof delay == "number" ? delay : 1;
 this.scrolldelay = typeof scrolldelay == "number" ? scrolldelay : 10;
 if(typeof arguments[5] == "number")
 {
  this.MinHeight = arguments[5];
 }
 else
 {
  if(this.ID.style.height)
  {
   this.MinHeight = this.ID.offsetHeight;
  }
  else
  {
   this.MinHeight = 0;
   this.ID.style.height = "0px";
  }
 }
 if(typeof arguments[4] == "number")
 {
  this.MaxHeight = arguments[4];
 }
 else
 {
  var _h = this.ID.offsetHeight;
  var _display = this.ID.style.display;
  this.ID.style.display = '';
  this.ID.style.visibility = 'hidden';
  this.ID.style.height = '';
  this.MaxHeight = this.ID.offsetHeight;
  this.ID.style.visibility = 'visible';
  this.ID.style.display = _display;
  this.ID.style.height = _h + 'px';
 }
 this.before = [];
 this.after = [];
 var intervalId = null;
 var a = this;
 
 function show()
 {
  try{ a.dobefore(); }catch(e){ }
  var h = a.ID.offsetHeight;
  a.ID.style.display = '';
  a.ID.style.height = (h + 1) + "px";
  if(a.ID.offsetHeight >= a.MaxHeight)
  { 
   setTimeout(shut, a.stay * 1000);
  }
  else
  {
   setTimeout(show, a.scrolldelay); 
  }
 }
 
 function shut()
 {
  var h = a.ID.offsetHeight; 
  a.ID.style.height = (h - 1 < 0 ? 0 : h - 1) + "px";
  if (a.ID.offsetHeight <= a.MinHeight)
  { 
   if(a.MinHeight == 0) a.ID.style.display = "none";
   try{
    a.doafter();
   }catch(e){
    
   }
  }
  else
  {
   setTimeout(shut, a.scrolldelay); 
  }
 }
 
 this.show = show;
 this.shut = shut;
 setTimeout(show, this.delay * 1000);
}

slider.prototype.addbefore = function(func)
{
 this.before.push(func);
}

slider.prototype.dobefore = function()
{
 for(var i = 0; i < this.before.length; i++)
 {
  this.before[i]();
 }
}

slider.prototype.addafter = function(func)
{
 this.after.push(func);
}

slider.prototype.doafter = function()
{
 for(var i = 0; i < this.after.length; i++)
 {
  this.after[i]();
 }
}
</script>

附:定时展开收缩广告特效代码的完整代码