JS幻灯片与CSS背景颜色变化

JS slideshow with a background color change in CSS

本文关键字:颜色 变化 背景 CSS 幻灯片 JS      更新时间:2023-09-26

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

Javascript运行正常,但CSS背景不正确。这是两者的代码。Javascript代码借用了W3Schools的自动幻灯片演示示例。

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
}

由于缺乏HTML,我只能假设你想要什么,但问题在于CSS:

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

从到关键帧如下(from(0%){} to(100%){}是自动的):

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

关键帧文档是一个不错的来源。

这里有一些替代CSS。

CSS:

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

使用转换,您可以使用JS更改样式以慢慢转换到所需的颜色,只需更改元素的background-color,您就必须执行element.style.backgroundColor='red'