Swiper,swiper-slide背景颜色不正确

时间:2017-09-17 03:53:13

标签: swiper

我希望这三种幻灯片背景颜色轮流使用。

像这样:绿色(1) - >橙色(2) - >绿色(3) - 橙色(1)......

但目前的行为并不像预期的那样。

我该如何解决这个问题?

window.onload = function() {

  const defaultOptions = {
    speed: 2000,
    autoplay: true,
    spaceBetween: 4,
    direction: 'vertical',
    loop: true,
    slidesPerView: 'auto',
    watchSlidesVisibility: true
  };

  const swiper = new Swiper('.swiper-container', defaultOptions)
}
.swiper-container{
    height: 52px;
  }

  .swiper-slide{
    display: inline-block;
    width: auto;
    height: 26px;
    max-width: 100%;
    padding: 0 10px;
  }
<script src="https://cdn.staticfile.org/Swiper/3.4.2/js/swiper.js"></script>
<link href="https://cdn.staticfile.org/Swiper/3.4.2/css/swiper.css" rel="stylesheet"/>

<div class='swiper-container'>
  <div class='swiper-wrapper'>
    <div class='swiper-slide' style='background: green'>message 1</div>
    <div class='swiper-slide' style='background: orange'>message 2</div>
    <div class='swiper-slide' style='background: green'>message 3</div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您可以在备用幻灯片上设置背景颜色,但真正的技巧是在为循环功能重新生成重复的幻灯片时切换它们。

我已使用变量修改了您提供的代码,以便在幻灯片开始更改时跟踪进度和测试条件。

&#13;
&#13;
window.onload = function() {

  var lastIndex = 0;

  const defaultOptions = {
    speed: 2000,
    autoplay: true,
    spaceBetween: 4,
    direction: 'vertical',
    loop: true,
    slidesPerView: 'auto',
    watchSlidesVisibility: true,
    onSlideNextStart: function(swiperObj) {
      if ( swiperObj.activeIndex < lastIndex ) {
        swiperObj.container[0].classList.toggle('alt-bg');
      }
      lastIndex = swiperObj.activeIndex;
    }
  };

  const swiper = new Swiper('.swiper-container', defaultOptions)
}
&#13;
.swiper-container{
    height: 52px;
  }

  .swiper-slide{
    display: inline-block;
    width: auto;
    height: 26px;
    max-width: 100%;
    padding: 0 10px;
    background: green;
  }

  .swiper-slide:nth-child(2n+1){
    background: orange;
  }

  .alt-bg .swiper-slide{
    background: orange;
  }
  .alt-bg .swiper-slide:nth-child(2n+1){
    background: green;
  }
&#13;
<script src="https://cdn.staticfile.org/Swiper/3.4.2/js/swiper.js"></script>
<link href="https://cdn.staticfile.org/Swiper/3.4.2/css/swiper.css" rel="stylesheet"/>

<div class='swiper-container'>
  <div class='swiper-wrapper'>
    <div class='swiper-slide'>message 1</div>
    <div class='swiper-slide'>message 2</div>
    <div class='swiper-slide'>message 3</div>
  </div>
</div>
&#13;
&#13;
&#13;