javascript - CSS+Javascript 交换不同的背景图片

标签 javascript html css background

我想通过点击更改至少三个横幅(背景图片)。它可以交换两个横幅,但如何按顺序交换三个以上的图像。另外,我想在交换图像时有过渡效果。谁能帮忙。

$(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)
...

您可以找到完整的代码笔和动画 here

关于javascript - CSS+Javascript 交换不同的背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168281/

相关文章:

JavaScript bencode 二进制长度

html - CSS - 在所有屏幕尺寸下渲染视口(viewport)下方 10% 的图像

android - android chrome 上的居中 block

html - CSS 三列调整大小问题

javascript - "popover"Twitter Bootstrap css/javascript 库上的问题

css - SVG 中文本的背景色

javascript - 如何获取 JqWidgets 网格中所有未选择的行索引的列表

javascript - Pinterest 风格的网格

javascript - Object.create vs new 在原型(prototype)继承方面

javascript - 在平移之前旋转还是在旋转之前平移?它有什么区别?