【问题标题】:Is there a work around for adding the '.active' class to the first slide of a Bootstrap 4 Carousel?是否可以将“.active”类添加到 Bootstrap 4 Carousel 的第一张幻灯片?
【发布时间】:2017-12-28 06:38:41
【问题描述】:

我正在我的网站上实施Bootstrap 4 Carousel,但遇到了一个问题:

Carousel 似乎需要在第一张幻灯片上设置 .active 类,否则它将无法工作。通过我在 CMS 中实现 Carousel 的方式,我为幻灯片使用了单个模板文件(其中包含动态内容),允许我实现无限数量的幻灯片。但是,我无法将初始幻灯片设置为具有 .active 类,而该类没有出现在所有幻灯片上,并且会破坏轮播。

我可以使用一些 JQuery 将该类添加到幻灯片的第一个实例中,但我希望有办法解决这个问题(对我来说,这似乎有点疏忽了 Bootstrap)。

有人知道这是否可能吗?

【问题讨论】:

  • 您的 CMS 使用什么语言?为什么不能在条件中编写代码来为第一张幻灯片添加活动类?
  • 我可以,但如果有我不知道的正确引导方式来做这件事,我想避免这样的事情。
  • @MeltingDog 直接将它添加到 HTML。这是唯一的方法(没有任何额外的不必要的编码)
  • 似乎 CMS 中的代码应该创建正确的引导方式并将活动添加到第一张幻灯片。我相信你有一个添加幻灯片的循环,你需要添加的只是一个 if slide = 1 添加活动类。

标签: jquery css twitter-bootstrap


【解决方案1】:

您可以使用 jquery 添加活动类。这将解决问题

$(document).ready(function () {
  $('#myCarousel').find('.item').first().addClass('active');
});
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Carousel Example</h2>  
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item">
        <img src="http://cableandmedia.com/pnnm/assets/images/hospital/hos6.jpg" alt="Los Angeles" style="width:100%;">
      </div>

      <div class="item">
        <img src="http://cableandmedia.com/pnnm/assets/images/hospital/hos4.jpg" alt="Chicago" style="width:100%;">
      </div>
    
      <div class="item">
        <img src="http://cableandmedia.com/pnnm/assets/images/hospital/hos7.jpg" alt="New york" style="width:100%;">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>

</body>
</html>

【讨论】:

  • 是的,这就是我最终所做的。只是不确定 BS4 是否已经有办法做到这一点
猜你喜欢
  • 2017-09-27
  • 2019-02-15
  • 2013-04-29
  • 2017-05-22
  • 1970-01-01
  • 2020-10-05
  • 2014-10-09
  • 2016-10-16
  • 2021-07-30
相关资源
最近更新 更多