2016-05-16 64 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

好的....问题我很抱歉....学习过程。我非常感谢你 –