29 tháng 7 2011

Rotating banner script

Trong quá trình làm website thanhlongcandy.com.vn, mình đã viết 1 đoạn code javascript nho nhỏ để làm hiệu ứng cho banner.

HTML

<div id="banners" style="width:931px;position:absolute">
 <a href="#" id="banner_1"><img border=0 src="banner_img931x375.png" width="931" height="375" alt="" /></a>
 <a href="#" id="banner_2"><img border=0 src="banner_img_2_931x375.png" width="931" height="375" alt="" /></a>
 <a href="#" id="banner_3"><img border=0 src="banner_img_3_931x375.png" width="931" height="375" alt="" /></a>
</div>

Javascript

var index;
 var interval;
 var animation_is_done = true;//when aniamtion is occur, we can not click on it
 index = 1; 
  
 function slideLeft(){
  if(index==3){
   index=0;
   jQuery("#banners").animate({left:'0'},2000,function(){});   
   index++;
  }
  else{
   jQuery("#banners").animate({left:'-=931'},2000,function(){});
   index++;   
  }
  if(index==1)jQuery(".b3").removeClass("active");  
  jQuery(".b"+(index-1)).removeClass("active");
  jQuery(".b"+index).addClass("active");
  
 }
 
 function slideTo(pos){
  clearInterval(interval);
  
  left = 931*pos;
  jQuery("#banners").animate({left:'-'+left},2000,function(){});
  jQuery(".bnbt_w ul li a").each(function(){jQuery(this).removeClass("active")})
  jQuery(".b"+(pos+1)).addClass("active");
  
  index = pos+1;
  interval=setInterval("slideLeft()",5000);
 }
  
 function fade(){  
  if(animation_is_done==false)return false;
  
  animation_is_done = false;
  
  clearInterval(interval);
  
  for(i=1; i<=3; i++)
  {
   if(i!=index){
    jQuery("#banner_"+i).css("style","z-index:0");
    jQuery("#banner_"+i).fadeOut(1000);
   }   
  }
  
  jQuery("#banner_"+index).css("style","z-index:99");
  jQuery("#banner_"+index).fadeIn(3000,function(){animation_is_done=true});  
    
  jQuery(".bnbt_w ul li a").each(function(){jQuery(this).removeClass("active")})
  jQuery(".b"+(index)).addClass("active");
  index++;
  if(index>3)index=1;
  
  interval = setInterval("fade()",5000);
 } 
  
    jQuery(document).ready(function(){
  interval = setInterval("fade()",5000);
  
  jQuery(".b1").click(function(){index=1;fade();});
  jQuery(".b2").click(function(){index=2;fade();});
  jQuery(".b3").click(function(){index=3;fade();}); 
    });

Không có nhận xét nào: