【问题标题】:JS slideshow with a background color change in CSS具有 CSS 中背景颜色更改的 JS 幻灯片
【发布时间】:2016-05-23 09:39:17
【问题描述】:

我决定尝试使用 CSS 中的动画为背景创建幻灯片,并使用 Javascript 中的第二层使用Jquery

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
}

【问题讨论】:

  • 它实际上不起作用

标签: javascript jquery css


【解决方案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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2017-11-17
    • 2013-01-08
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多