2016-05-16 48 views
-5

我決定嘗試使用Jquery使用CSS中的背景用第二層Javascript創建幻燈片。在CSS中使用背景顏色變化的JS幻燈片

Javascript運行正常,但CSS背景不正確。這是兩者的代碼。該代碼是從W3School的'Automatic Slideshow example借來的。

CSS:

body { 
    animation-name: change_color; animation-duration: 10s; 
    animation-timing-function: ease-in-out; 
    animation-iteration-count: infinite; 
} 
@keyframes change_color { 
    { from (0%) } 
    { to (100%) } 
} 

的Javascript:

var slideIndex = 0; 
carousel(); 

function carousel() { 
    var i = 0; 
    var x = document.getElementsByClassName("a"); 
    for (i = 0; i < x.length; i++) { 
    x[i].style.display = "none"; 
    } 
    slideIndex++; 
    if (slideIndex > x.length) { 
    slideIndex = 1 
    } 
    x[slideIndex - 1].style.display = "block"; 
    setTimeout(carousel, 10000); // Change image every 2 seconds 
} 
+0

它實際上並不工作 –

回答

1

好吧,我只能假設你想要什麼,由於缺乏HTML的,但問題在於CSS:

@keyframes change_color{ 
    {from (0%)} 
    {to (100%)} 
} 

自 - 關鍵幀是這樣的(from(0%){} to(100%){}是自動的):

@keyframes change_color{ 
    from { 
    background-color: red; 
    } 
    to { 
    background-color: blue; 
    } 
} 

keyframes documentation是一個很好的來源。

這是一些備用的CSS。

CSS:

body { 
    background-color: black; /* whatever color you want */ 
    transition: background-color, 2s, ease-in-out, infinite; 
} 

使用transitions,您可以使用JS來改變風格,慢慢過渡到想要的顏色,只是改變了元素的background-color,你必須做element.style.backgroundColor='red'

+0

好的....問題我很抱歉....學習過程。我非常感謝你 –