欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jQuery定义背景动态切换效果的方法教程

程序员文章站 2022-03-16 15:48:45
本文实例讲述了jquery定义背景动态切换效果的方法。分享给大家供大家参考。具体如下: 通过下面的jquery插件,你可以将图片放在一个数组里,然后告诉jquery图片需要在什么...

本文实例讲述了jquery定义背景动态切换效果的方法。分享给大家供大家参考。具体如下:

通过下面的jquery插件,你可以将图片放在一个数组里,然后告诉jquery图片需要在什么地方背景轮换

(function($){
 var defaultsettings;
 var pfg, pbg;
 var fadeinterval;
 var fqtimer;
 var currimg = 0;
 var displimg = 0;
 var running = false;
 // setup settings and initialize the plugin
 $.fn.bgfade = function(settings, callback){
  defaultsettings = $.extend({
   frequency: 5000,
   speed: 10,
   images: [],
   position: "center center",
   fgz: 1,
   bgz: 0
  }, settings);
  var c = 0;
  $(this).each(function(){
   if(c == 0) pfg = $(this);
   if(c == 1) pbg = $(this);
   c++;
  });
  setbackgrounds();
  if(typeof callback == "function"){
   callback();
  }
  return this;
 };
 // start the fadder
 $.fn.start = function(){
  fqtimer = settimeout(function(){
  nextfade()},defaultsettings.frequency
  );
  running = true;
  return this;
 };
 // stop the fadder
 $.fn.stop = function(){
  clearinterval(fadeinterval);
  cleartimeout(fqtimer);
  running = false;
  return this;
 }
 // get the current image info {array id, image url}
 $.current = function(){
  return {pos: displimg, url: defaultsettings.images[displimg]}
 }
 // set the first two backgrounds
 function setbackgrounds(){
  image1 = defaultsettings.images[0];
  image2 = defaultsettings.images[1];
  pfg.css({
   backgroundimage: "url('"+image1+"')",
   zindex: defaultsettings.fgz,
   backgroundposition: defaultsettings.postion
  });
  pbg.css({
   backgroundimage: "url('"+image2+"')",
   zindex: defaultsettings.bgz,
   backgroundposition: defaultsettings.postion
  });
  currimg = 1;
  displimg = 0;
 }
 // set the next background after a fade completes
 function setnextbackground(){
  next = arraynext();
  image = defaultsettings.images[next];
  pbg.css({
   backgroundimage: "url('"+image+"')"
  });
  settimeout(function(){nextfade()}, defaultsettings.frequency);
 }
 // run a fade
 function nextfade(){
  fadeinterval = setinterval(function(){fadeit()}, 30);
 }
 // decrement the opacity of the p
 function fadeit(){
  if(pfg.css("opacity") == ''){
   op = 1;
  }else{
   op = pfg.css("opacity");
  }
  op -= ((1000 * defaultsettings.speed) / 30) * 0.0001;
  pfg.css("opacity", op);
  if(op <= 0){
   bg = pbg;
   bgimg = pbg.css("background-image");
   pfg.css("opacity", "1");
   pfg.css("background-image", bgimg);
   clearinterval(fadeinterval);
   setnextbackground();
   displimg = arraycurrent();
  }
 }
 // get the next item in the array
 function arraynext(){
  var next = currimg + 1;
  if(next >= defaultsettings.images.length){
   next = 0;
  }
  currimg = next;
  return next;
 }
 // get the current item in the array
 function arraycurrent(){
  var cur = currimg - 1;
  if(cur < 0)
   cur = defaultsettings.images.length - 1;
  return cur;
 }
})(jquery);

希望本文所述对大家的jquery程序设计有所帮助。