如何在运行时更改BS轮播间隔?

时间:2019-06-29 13:51:28

标签: javascript bootstrap-4 carousel

我知道您可以通过以下方式设置引导轮播间隔:

$('.carousel').carousel({interval: 1000 });

我的问题是如何将间隔更改为(例如)10秒后的2秒?

setTimeout(function(){ }, 10000);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以先将interval设置为1000,然后再将其设置为2000。这不是技巧,不是官方的方法。

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
    <ol class="carousel-indicators">
        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
        <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
        <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
    </ol>
    <div class="carousel-inner">
        <div class="carousel-item active">
            <img src="https://picsum.photos/1920/1080?random=1" class="d-block w-100" alt="img">
        </div>
        <div class="carousel-item">
            <img src="https://picsum.photos/1920/1080?random=2" class="d-block w-100" alt="img">
        </div>
        <div class="carousel-item">
            <img src="https://picsum.photos/1920/1080?random=3" class="d-block w-100" alt="img">
        </div>
    </div>
    <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
    </a>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>

    $('.carousel').carousel({
        interval: 1000
    });
    
    setInterval(() => {
        $('.carousel').carousel('dispose')
        $('.carousel').carousel({
          interval: 2000
        });
    }, 10000)

</script>