CSS+Javascript交换不同的背景图像

CSS+Javascript swap different background image

本文关键字:背景 图像 交换 CSS+Javascript      更新时间:2023-09-26

我想通过点击改变至少三个横幅(背景图像)。它可以交换两个横幅,但如何交换三个以上的图像顺序。此外,我想有过渡效果,当我交换图像。有人能帮忙吗?

$(document).ready(function(){
  $("#next-section").click(function(){
    $("#banner").css("background-image", "url('images/top8.jpg')");
  });
});
#banner {
  background-image: url("images/top7.jpg");
  background-position: center center;
  background-size: cover;
  height: 30em;
  text-align: left;
  position: relative;
  -ms-overflow-style: scrollbar;
}
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<div id="logo" style="height:200px">
  <section id="banner"  >
    <div id="back-section">
      <a class="back"><span></span></a>
    </div><!-- /.next-section -->
    <div id="next-section" >
      <a class="next"><span></span></a>
    </div><!-- /.next-section -->
    <div class="inner">
      <div class="logo"><h12><img style="vertical-align:middle" src="images/hi5logo.png" alt="" width="50">  Interactive Game </h12> </div>
    </div>
  </section>
</div>

我已经设置了一个脚本,以便您的背景从数组循环,当到达最后一个背景时,第一个背景被设置为下一个。

var arrayOfBackgrounds=["http://placehold.it/300x200","http://placehold.it/222x222","http://placehold.it/333x333"];
var currentBackground=0;
$("#next-section").click(function(){
    $("#banner").css("background-image", "url('"+arrayOfBackgrounds[currentBackground]+"')");
        currentBackground++;
        currentBackground=currentBackground % arrayOfBackgrounds.length;
}

currentBackground是背景的索引,表示currentBackground%arrayOfBackgrounds.length的行将索引除以可能的背景数量并返回余数。
模数运算符是这样工作的:

0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0 (the remainder here is 0)
...

你可以在这里找到完整的代码依赖以及动画