开发者

jQuery background-image animation

开发者 https://www.devze.com 2022-12-18 08:48 出处:网络
How do I animate between two PNG images in jQuery? Is this possible? Something like t开发者_开发技巧he CSS 3 transition when you transit between one color to another, but I need an image to an image

How do I animate between two PNG images in jQuery? Is this possible?

Something like t开发者_开发技巧he CSS 3 transition when you transit between one color to another, but I need an image to an image transition.


Check out this plugin by Jack Moore called jQuery Blend.

Edit: Opps two images, sorry. How about this plugin then?


Ok, if you aren't happy with a plugin then try this. I posted a demo here.

CSS/HTML

<style type="text/css">
.wrap {
 margin: 50px auto;
 width: 200px;
 height: 200px;
 background: #555;
 position: relative;
}
.display1, .display2 {
 position: absolute;
 top: 0;
 left: 0;
}
</style>
<div class="wrap">
 <div class="display1"></div>
 <div class="display2"></div>
</div>

Script

$(document).ready(function(){
 var bkgImgs = ([
  ['http://i50.tinypic.com/2iiz9cm.gif', 86, 86],
  ['http://i45.tinypic.com/dop26e.png', 128, 128],
  ['http://i48.tinypic.com/xcosnq.png', 64, 64]
 ]);
 var delay = 5000;
 var transition = 1000;

 var i = 0;
 var l = bkgImgs.length-1;
 imgs = function(x){
  return {
   background: 'url(' + bkgImgs[x][0] + ') no-repeat center center',
   width:      bkgImgs[x][1],
   height:     bkgImgs[x][2],
   left:       $('.wrap').width()/2 - bkgImgs[x][1]/2,
   top:        $('.wrap').height()/2 - bkgImgs[x][2]/2
  }
 }
 next = function(){
  var oldpic = imgs(i);
  i++;
  if (i > l) i = 0;
  var newpic = imgs(i);
  $('.display2').css(oldpic).show();
  $('.display1').hide().css(newpic).fadeIn(transition);
  $('.display2').fadeOut(transition);
  setTimeout( function(){ next() }, delay );
 }
 next();
})


This might help: http://snook.ca/archives/javascript/jquery-bg-image-animations/


When you say "Animate between two images" do you mean you want them to fade into one another?

I think what you would have to do is basically create two divs that float underneath the main content (using z-index) and then fade between them by:

  1. putting image B (hidden) behind image A (say, by setting image B's z-index to 10 and image A z-index to 20)

  2. showing image B using .show() [it would still be hidden behind A]

  3. Fading out image A using .fadeOut()

repeat 1-3 switch A and B

If you want this animation to be ongoing, you could use window.setInterval() to run the code every so often. You could have a variable current_bg that stores either A or B to keep track of which way you should make the switch.

0

精彩评论

暂无评论...
验证码 换一张
取 消