如何创建JQuery / CSS3块转换效果?

时间:2014-09-10 11:32:04

标签: jquery css3 css-transitions transition

我已经看过许多JQuery插件的例子,当图像从一个图像转换到另一个图像时,这些插件会创建具有许多不同风格效果的幻灯片。

我在过去一天左右一直在玩这个,并且有一些使用JQuery的幻灯片的好工作示例,并且想要开始使用一些更奇特的过渡而不是从左到右的列表中的简单滑动图像对,或将一个图像淡出,另一个图像淡出。

我想自己倾向于如何做到这一点,而不是使用插件,并想知道是否有人有一个简单的例子,说明我将如何从一个图像转换到另一个图像并具有块效果(或其他其他奇特效果),其中一个图像被另一个图像替换为由较小的块组成的淡入淡出等等?

由于

1 个答案:

答案 0 :(得分:1)

<强> jsBin demo

enter image description here

  • 创建一个兄弟div元素的堆栈,
  • 取决于当前计数器将[图片网址设置为background-image
  • 计算每个元素位置并将完全相同的逆( - ) [值应用于它的background-position属性。
  • 将下一张图片设置为图库背景(将不会显示)
  • 使用效果(opacity0,top,left ...)
  • 为当前的DIV堆栈设置动画
  • 现在画廊bg是可见的,我们需要创建一个具有相同图像的新DIV堆栈。

var $gal   = $('#gallery');
var width  = $gal.outerWidth();
var height = $gal.outerHeight();
var img = [
  "1.jpg",
  "2.jpg",
  "3.jpg",
];
var n = img.length;
var c = 0;

// Effects:
var fx = [
  {top: -height},
  {opacity: 0},
  {top:  height},
  {left: -width}
];

// Random FX:
function randFX(){
  return fx[ Math.floor(Math.random()*fx.length) ];
}

// Preload all images:
for(var i=0; i<img.length; i++){
  var nImg = new Image();
  nImg.src = img[i];
}

// Creates a new set of 5 DIV:
function div5(){
  var w5 = width/5 ;
  for(var i=0; i<5; i++){
    var div = $("<div />", {
      'class' : "div5",
      'style' : "background: url("+img[c]+") "+ (-w5*i) +"px 0"
    });
    $gal.append(div);
  }
}
div5();

// Animates current set
function animDiv5(){

  // Prepare next image as gallery normal background image
  $gal.css({background: "url("+ img[c] +")"});

  // Generate a random animation
  var animfx = randFX();  

  // Animate Current DIVs
  $("div", $gal).each(function(i){
    $(this).stop().delay(70*i).animate( animfx, function(){
      if(!$(this).next()[0]){ // Once all are animated...
         $gal.html(""); // Remove DIVs
         // The gallery BG was visible for a tily amount of time,
         // now cover it with the same image but again splitted in DIVs
         div5(); 
      }
    });
  });
}



// Do it!
$("button").click(function(){
    c = ++c % n; // Increment counter
    animDiv5();
});

在上面的代码中,你可能想要确保在允许另一个触发器之前没有当前动画运行,我已经向你展示了基本原理。
另一种使同一个画廊完美运行的方法是使用JS only 来创建DIV元素,计算BG位置并触发事件,
使用增强的CSS3过渡创建所需的所有动画。