在CSS

时间:2016-05-16 02:07:49

标签: javascript jquery css

我决定尝试使用CSS for background中的动画创建幻灯片,并使用Jquery在Javascript中创建第二层。

Javascript运行正常,但CSS背景不正确。这是两者的代码。 Javascript代码来自W3Schools' 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
}

1 个答案:

答案 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'。< / p>