在身体中交叉淡化背景图像

时间:2017-08-19 18:49:09

标签: javascript jquery html css

我有下一个问题:我想用计时器交叉淡化<body>标签的不同背景图像。你可以看到here我想要实现的一个例子。 问题是,我是这些东西的新手,无法弄清楚如何做到这一点......我见过很多帖子,但它们只会让我更加困惑!

我的HTML代码:

<body id="one" onload="startTimer()">
<!-- Some other tags -->
</body>
<script type = "text/javascript">
    function displayNextImage() {
        x = (x === images.length - 1) ? 0 : x + 1;
        var url = "url(" + images[x] + ")";
        $("#one").css('background-image', url);
    }

    function startTimer() {
      setInterval(displayNextImage, 6000);
    }

    var images = [], x = -1;
    images[0] = "someimage1.jpg";
    images[1] = "someimage2.jpg";
    images[2] = "someimage3.jpg";
</script>

和我的CSS代码:

body {
    background-image: url("images/forest1.jpeg");
    background-size: cover;
}

我愿意接受建议,我的意思是,如果有更好的方法可以做到这些,那太好了!我只想获得与上面显示的网站相同的观点!

提前致谢!

2 个答案:

答案 0 :(得分:2)

您不需要任何JavaScript,您可以使用CSS动画实现它:

body {
    background-size: cover;
}

@-webkit-keyframes changeBckg {
  0% {  background-image: url("https://unsplash.it/1000?image=1080"); }
  25% {  background-image: url("https://unsplash.it/1000?image=1081"); }
  50% { background-image: url("https://unsplash.it/1000?image=1064"); }
  75% {background-image: url("https://unsplash.it/1000?image=1078"); }
  100% {background-image: url("https://unsplash.it/1000?image=1080"); }
}

@keyframes changeBckg {
  0% {  background-image: url("https://unsplash.it/1000?image=1080"); }
  25% {  background-image: url("https://unsplash.it/1000?image=1081"); }
  50% { background-image: url("https://unsplash.it/1000?image=1064"); }
  75% {background-image: url("https://unsplash.it/1000?image=1078"); }
  100% {background-image: url("https://unsplash.it/1000?image=1080"); }
}

.letterAnimation {
  -webkit-animation: changeBckg 16s ease infinite;
  animation: changeBckg 16s ease infinite;
}
<body class="letterAnimation">
  
</body>

答案 1 :(得分:1)

一个简单的CSS解决方案,它使用CSS动画@keyframes;您可以将相同的代码应用于html页面的正文。

@keyframes cf4FadeInOut {
  0% {
    opacity: 1;
  }
  17% {
    opacity: 1;
  }
  25% {
    opacity: 0;
  }
  92% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

#cf4a img:nth-of-type(1) {
  animation-delay: 6s;
}

#cf4a img:nth-of-type(2) {
  animation-delay: 4s;
}

#cf4a img:nth-of-type(3) {
  animation-delay: 2s;
}

#cf4a img:nth-of-type(4) {
  animation-delay: 0;
}

#cf4a img {
  position: absolute;
  top: 0;
  left: 0;
  animation: cf4FadeInOut 5s infinite;
}
<div id="cf4a" class="shadow cf4FadeInOut">
  <img src="https://placeimg.com/150/150/01">
  <img src="https://placeimg.com/150/150/02">
  <img src="https://placeimg.com/150/150/03">
  <img src="https://placeimg.com/150/150/04">
</div>