class 在 Bootstrap 旋转木马上发生变化时更改背景

Change background when active class changes on Bootstrap Carousel

我想在每次滑块滑动时更改容器的背景。我认为我需要检查是否/何时项目的 class 因为活动。我还想知道是否没有我应该听的事件。这是我正在处理的 jsfiddle:

https://jsfiddle.net/podbarron/nj04xms5/

$(function(){
$('#carousel-indicators').on('click', 'li', function(){

});
});

谢谢!

$(function(){
    $('#target1').on('click', function(){
        $('#landingContainer').css('background-color', 'green');
    });
});

Bootstrap 旋转木马有一个事件会触发 on/after 每次幻灯片切换。你应该可以使用它。

示例:https://jsfiddle.net/nj04xms5/7/

事件中的 js 非常基础,但只是给你一个想法。

如果您想从中获取信息(即 ID),

e.relatedTarget 将为您提供当前幻灯片

$('#carousel-example-generic').on('slide.bs.carousel', function(e) {
      if(e.relatedTarget.id == 'firstSlide'){
          $("#landingContainer").css('background-color', 'orange');
      } else if(e.relatedTarget.id == 'secondSlide'){
          $("#landingContainer").css('background-color', 'green');
      }
})
var randomColors    = ["green", "red", "white"];
var clrI    = 0;
$('#carousel-example-generic').on('slide.bs.carousel', function(e) {
    $(this).css('background-color', randomColors[clrI]);
    clrI++;
    if(clrI>=randomColors.length) {
        clrI    = 0;
    }
});

您可以使用数组来定义颜色,并按顺序应用这些颜色..

Bootstrap 触发 events on carousel transitions, which is the first way you could improve this. IMHO the second big improvement would be to avoid a verbose if/else statement and define the target color on each slide, like I've done in this fiddle

JS

$(function(){
    $('.carousel').on('slide.bs.carousel', function(event) {
        color = $(event.relatedTarget).attr('data-new-color');
        if (color) {
            $('#landingContainer').css('background-color', color)
        }
    })
});

轮播元素示例

<div id="secondSlide" class="item" data-new-color="blue">
  <img src="http://dummyimage.com/1080x400/0011ff/000" alt="...">
  <div class="carousel-caption">
    ...
  </div>
</div>