如何循环bootstrap Carousels?

时间:2015-08-10 06:38:57

标签: php twitter-bootstrap-3

我正在尝试从mysql数据循环播放。以下是我的代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

</head>
<body>
<div class="bs-example">
    <div id="myCarousel" class="carousel slide" data-interval="2000" data-ride="carousel">
        <!-- Carousel indicators -->
        <ol class="carousel-indicators">
        @for($i=0;$i<=count($data);$i++)
            <li data-target="#myCarousel" data-slide-to="{{$i}}" class=""></li>
            @endfor;
        </ol>   
        <!-- Wrapper for carousel items -->
        <div class="carousel-inner">
            <div class="active item">
                <img src="images/1.jpg" alt="First Slide">
                <div class="carousel-caption">
                  <h3>First slide label</h3>
                  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                </div>
            </div>

            @foreach($data as $val)


            <div class="item">
                <img src="{{ $val['featured_image']}}" alt="Second Slide">
                <div class="carousel-caption">
                  <h3>{{ $val['title']}}</h3>
                  <p>{{ $val['description']}}</p>
                </div>
            </div>
            @endforeach

        </div>

        <a class="carousel-control left" href="#myCarousel" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left"></span>
        </a>
        <a class="carousel-control right" href="#myCarousel" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
        </a>
    </div>
</div>
</body>
</html>     

以上代码仅在我添加以下行

时才有效
<div class="active item">
                <img src="images/1.jpg" alt="First Slide">
                <div class="carousel-caption">
                  <h3>First slide label</h3>
                  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                </div>
            </div>

如果我删除上面的代码然后滑块不显示任何images.i认为我需要保持我的拳头滑块图像需要激活。如何实现,而不添加默认的活动代码?提前谢谢

1 个答案:

答案 0 :(得分:5)

是的,第一张幻灯片必须有active类才能在init上自动显示它。

试试这个:

{{--*/ $isFirst = true; /*--}}
@foreach($data as $val)
  <div class="item{{{ $isFirst ? ' active' : '' }}}">
      <img src="{{ $val['featured_image']}}" alt="Second Slide">
      <div class="carousel-caption">
        <h3>{{ $val['title']}}</h3>
        <p>{{ $val['description']}}</p>
      </div>
  </div>
  {{--*/ $isFirst = false; /*--}}
@endforeach

所以我创建了$isFirst变量,在第一张幻灯片打印之前保留true的变量。这样我们就可以为第一张幻灯片添加active类,而不为其他幻灯片添加。{/ p>