2016-04-20 45 views
0

基本上,我有這個代碼掛鉤到網站中的某個元素並覆蓋它的內容。在這個例子中,它覆蓋了現有的文本,以便每隔一段時間更改一次。但是,當它在預設的文本行中循環時,它只是跳躍而沒有動畫。是否可以在預設文本之間添加淡入淡出動畫?如何在現有的js代碼中添加淡入淡出效果

下面是代碼:

var text = ["Question Everything!", "Envision the future!", "Change your perspective!"]; 
    var counter = 0; 
    var elem = document.getElementById("slogantxt"); 
    setInterval(change, 3500); 

    function change() { 
     elem.innerHTML = text[counter]; 
     counter++; 
    if(counter >= text.length) { counter = 0; } 
    } 
+0

看看[jQuery UI](https://jqueryui.com/)。 –

回答

0

隨着jQuery的你可以做這樣的事情:

$(document).ready(function(){ 
    var text = ["Question Everything!", "Envision the future!", "Change your perspective!"]; 
    var counter = 0; 
    setInterval(change, 3500); 
    function change() { 
    $("#slogantxt").fadeOut('fast',function(){//fade out the element 
     $(this).html(text[counter]).fadeIn('fast');//once fade out completes, change the element text and fade it back in 
    }); 

    counter++; 
    if(counter >= text.length) { counter = 0; } 
    } 
}); 
0

用JS就可以像下面

var text = ["Question Everything!", "Envision the future!", "Change your perspective!"]; 
var counter = 0; 
var elem = document.getElementById("slogantxt"); 
setInterval(change, 3500); 
function change() { 
fade(elem,function(){ 
    elem.innerHTML = text[counter]; 
    unfade(elem); 
}); 
counter++; 
if(counter >= text.length) { counter = 0; } 
} 


function fade(element,cbk) { 
    var op = 1; // initial opacity 
    var timer = setInterval(function() { 
     if (op <= 0.1){ 
      clearInterval(timer); 
      element.style.display = 'none'; 
      cbk(); 
     } 
     element.style.opacity = op; 
     element.style.filter = 'alpha(opacity=' + op * 100 + ")"; 
     op -= op * 0.1; 
    }, 50); 
} 

function unfade(element) { 
    var op = 0.1; // initial opacity 
    element.style.display = 'block'; 
    var timer = setInterval(function() { 
     if (op >= 1){ 
      clearInterval(timer); 
     } 
     element.style.opacity = op; 
     element.style.filter = 'alpha(opacity=' + op * 100 + ")"; 
     op += op * 0.1;   
    }, 10); 
} 

Ref:How to do fade-in and fade-out with JavaScript and CSS

1

CSS3 @keyframes動畫在這裏的重量要輕很多。

@keyframes fadeOutIn { 
    0% {opacity: 1;} 
    50% {opacity: 0;} 
    100% {opacity: 1;} 
} 

.fadeOutIn { 
    animation-name: fadeOutIn; 
    animation-duration: 200ms; 
} 

然後,只需在更改內部HTML時刪除並重新添加該類。

編輯:爲了簡單起見,我省去了必要的-webkit-前綴。別忘了!