首页 > 解决方案 > 使用脚本后无法获取背景图像以在网页上全屏显示

问题描述

我正在使用 bootstrap 4 编写登录页面,并试图让背景每隔几秒钟更改一次并且对移动设备友好。我想出了让图像发生变化的代码,但现在我不知道如何合并 img-responsive 类。

<section id="fh5co-home" data-section="home" style="background-image: url(images/pretty-bastard-client-lounge.jpg);" data-stellar-background-ratio="0.5">
    <script>
  var images = [
        "images/pretty-bastard-dallas-print-studio.jpg",
        "images/pretty-bastard-lobby.jpg",
        "images/pretty-bastard-sound-stage.jpg",
        "images/pretty-bastard-studio-walls.jpg",
  ]
  var imageHead = document.getElementById("fh5co-home");
  var i = 0;
  setInterval(function() {
      imageHead.style.backgroundImage = "url(" + images[i] + ")";
      i = i + 1;
      if (i == images.length) {
        i =  0;
      }
  }, 7000);
  </script>

这是CSS:

#fh5co-home {
  background-color: transparent;
  background-size: cover;
  position: relative;
  width: 100%;
  color: #fff;
}
@media screen and (max-width: 480px) {
  #fh5co-home {
    background-position: center center;
    background-attachment: initial;
  }
}

标签: javascripthtmlcssbootstrap-4

解决方案


没有高度,您可能不会等待 7 秒。你甚至没有结束部分的标签

<section id="fh5co-home" data-section="home" style="background-image: url(images/pretty-bastard-client-lounge.jpg);"
    data-stellar-background-ratio="0.5"> </section>
<script>
    var images = [
        "images/pretty-bastard-dallas-print-studio.jpg",
        "images/pretty-bastard-lobby.jpg",
        "images/pretty-bastard-sound-stage.jpg",
        "images/pretty-bastard-studio-walls.jpg",
    ]
    var imageHead = document.getElementById("fh5co-home");
    imageHead.style.backgroundImage = "url(images/pretty-bastard-dallas-print-studio.jpg";
    var i = 1;
    setInterval(function () {
        imageHead.style.backgroundImage = "url(" + images[i] + ")";
        i = i + 1;
        if (i == images.length) {
            i = 0;
        }
    }, 7000);


</script>

CSS:

#fh5co-home {
  /* background-color: transparent; */
  background-size: contain;
  background-repeat: no-repeat;
  position: relative;
  width: 100%;
  color: #fff;
  height:1000px;
  background-image: url("images/pretty-bastard-dallas-print-studio.jpg");
}
@media screen and (max-width: 480px) {
  #fh5co-home {
    background-position: center center;
    background-attachment: initial;
  }
}

推荐阅读