Bootstrap Carousel:将第一个循环图像设置为活动项

ccgok5k5  于 2023-02-06  发布在  Bootstrap
关注(0)|答案(3)|浏览(133)

我使用carousel来显示django应用程序中的一些图片。轮播显示图片列表中的图片,我想将第一个设置为active
这是我的剧本:

<div id="myCarousel" class="carousel slide" data-ride="carousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
            {% for publication in publication_list_carousel %}
              <li data-target="#myCarousel" data-slide-to="{{ publication.id }}" class="active"></li>
            {% endfor %}
          </ol>

          <!-- Wrapper for slides -->
          <div class="carousel-inner">
            <div class="item active">
              <img src="" alt="Cover page">
            </div>
            {% for publication in publication_list_carousel %}
              <div class="item">
                {% thumbnail publication.cover "200x200" crop="center" as im %}
                  <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
                {% endthumbnail %}
                <div class="carousel-caption">
                  <h3>{{ publication.title }} ({{ publication.pub_id }})</h3>
                </div>
              </div>
            {% endfor %}
          </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 class="item active">
    <img src="" alt="Cover page">
</div>

但我想激活第一个元素:

{% for publication in publication_list_carousel %}
    <div class="item">
        {% thumbnail publication.cover "200x200" crop="center" as im %}
             <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
        {% endthumbnail %}                   
    </div>
{% endfor %}

我怎么能做到呢?
谢谢大家!

    • 编辑:**

我在我的代码中尝试了类似这样的东西,但它不工作:

{% for publication in publication_list_carousel %}
    <div class="item {% if loop.index == 1 %} active {% endif %}">
lztngnrs

lztngnrs1#

我发现了一些关于Javascript的东西。我删除了代码中的active类,并写道:

<script>
  $(document).ready(function () {
    $('#myCarousel').find('.item').first().addClass('active');
  });
</script>

它似乎工作得很好;)

ykejflvf

ykejflvf2#

任何人谁是普通Javascript搜索答案这一点。

<script>
 document.querySelector(".carousel-inner").firstChild.classList.add("active");
</script>
syqv5f0l

syqv5f0l3#

您可以使用ff:

{% for publication in publication_list_carousel %}
   <div class="item {% if loop.first %} active {% endif %}">

   /* more codes */
{% endfor %}

{% for publication in publication_list_carousel %}
   <div class="item {% if loop.index0 == 0 %} active {% endif %}">
   
   /* more codes */
{% endfor %}

相关问题