2015-11-27 8 views
2

У меня есть следующий код, который будет исчезать, но мне интересно, есть ли способ справиться с этим в CSS.Как преобразовать эффект затухания jQuery в CSS?

$("#top").stop(true, true).delay(0).fadeTo(fadeTime * 100, 0); 
$("#back").stop(true, true).delay(0).fadeTo(fadeTime * 100, 1, function() { 
    if (curLoop < loops) { 
     if (curImg < imgNo) { 
      prevImg = curImg 
      curImg++ 
     } else { 
      prevImg = imgNo 
      curImg = 1; 
      curLoop++console.log("LOOP"); 
     } 

     document.getElementById("back").style.opacity = 0; 

     document.getElementById("top").style.opacity = 1; 

     document.getElementById("back").src = "frames/frame_" + curImg + ".jpg"; 
     document.getElementById("top").src = "frames/frame_" + prevImg + ".jpg"; 
    } else { 
     console.log("STOPPED"); 
     window.clearInterval(myVarSTD); 
    } 

    if (!initialized) { 
     myVarSTD = setInterval(function() { 
      startAnimation() 
     }, delay * 1000); 
     initialized = true; 
    } 
}); 
+1

Да с CSS3 легкостью. http://stackoverflow.com/questions/11679567/using-css-for-fade-in-effect-on-page-load –

+1

Это вызывает удивление. Вы специально спросили, как сделать вашу jquery-анимацию в CSS, и вы принимаете ответ jquery. –

ответ

3

Вы не можете зацикливаться на источниках изображения в чистой анимации CSS, но эффект с уменьшением затухания возможен при анимации CSS3. Здесь передние и задние изображения абсолютно позиционируются и с использованием анимации opacity они исчезают в бесконечном цикле. Я использовал 2 div с background-image, но вы можете сделать то же самое и для img.

Обратитесь к встроенным комментариям в фрагменте фрагмента, чтобы получить более подробное описание кода CSS анимации.

.front, 
 
.back { 
 
    position: absolute; /* absolute positioning puts them one on top of other */ 
 
    height: 200px; 
 
    width: 200px; 
 
    animation: fade-in-out 10s linear infinite; /* first is animation keyframe's name, second is the duration of the animation, third is timing function and fourth is iteration count */ 
 
} 
 
.front { 
 
    background-image: url(http://lorempixel.com/200/200/nature/1); 
 
} 
 
.back { 
 
    background-image: url(http://lorempixel.com/200/200/nature/2); 
 
    z-index: -1; /* keeps the element behind the front */ 
 
    animation-delay: 5s; /* delay is equal to half the animation duration because the back has to fade-in once the front has faded-out at 50% */ 
 
} 
 
@keyframes fade-in-out { /* animation settings */ 
 
    0%, 100% { 
 
    opacity: 1; /* at start and end, the image is visible */ 
 
    } 
 
    50% { 
 
    opacity: 0; /* at the mid point of the animation, the image is invisible */ 
 
    } 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> 
 
<div class='front'></div> 
 
<div class='back'></div>

0

jQuery Transit удивительный плагин, который имитирует функции анимации JQuery, но в CSS. С помощью CSS вы получаете гораздо более высокую частоту кадров!

3

Да, это так. Ваш код захватывает некоторые элементы, используя getElementById как back и top.

Вы можете использовать следующий код для изменения свойств CSS этих элементов:

$('#back').css({'opacity':'1'}); 

Реализовано в вашем коде:

$("#top").stop(true, true).delay(0).fadeTo(fadeTime*100, 0); 
      $("#back").stop(true, true).delay(0).fadeTo(fadeTime*100, 1, function(){ 
       if(curLoop<loops){ 
        if(curImg<imgNo){ 
         prevImg = curImg 
         curImg++ 
        }else{ 
         prevImg = imgNo 
         curImg = 1; 
         curLoop++ 
         console.log("LOOP"); 
        }    

    $('#back').css({'opacity':'0'}); 

    $('#top').css({'opacity':'1'}); 

        document.getElementById("back").src = "frames/frame_"+curImg+".jpg"; 
        document.getElementById("top").src = "frames/frame_"+prevImg+".jpg";    
       }else{ 
        console.log("STOPPED"); 
        window.clearInterval(myVarSTD); 
       } 

       if(!initialized){   
        myVarSTD = setInterval(function(){startAnimation()},delay*1000); 
        initialized = true; 
       } 
      });