【问题标题】:hasClass on Bootstrap 4 carousel not workingBootstrap 4轮播上的hasClass不起作用
【发布时间】:2021-09-30 13:06:16
【问题描述】:

我正在使用 Bootstrap 4 轮播构建一个基本的窄播系统。有些幻灯片包含图片,有些则包含 Youtube 视频。

当 div 包含 Youtube 视频时,我想在幻灯片处于活动状态时自动播放它,并在幻灯片不活动时停止它。但不知何故,hasClass 函数无法识别 id="video-1" 的 div 上的“活动”类。

<script type="text/javascript">
    $( document ).ready(function() {
        console.log( "document loaded" ); // added for testing
        if ($("#video-1").hasClass('active')) {
            console.log( "video loaded" ); // added for testing
            $("#ytplayer-1")[0].src += "&autoplay=1";
        } else {
            $("#ytplayer-1")[0].src += "&autoplay=0";
        }          
    });
</script>

这是我的html:

<div id="narrowcasting-carousel" class="carousel slide h-100" data-ride="carousel" data-interval="600000">
    <div class="carousel-inner h-100">
        <div class="carousel-item h-100 item-0" id="no-video" data-interval="10000">
             <img src="/images/image.png" />
        </div>
    </div>
    <div class="carousel-inner h-100">
        <div class="carousel-item h-100 item-1 active" id="video" data-interval="20000">
             <iframe id="ytplayer-1" width="100%" height="100%" src="https://www.youtube.com/embed/[CODE_HERE]?controls=0&amp;loop=0&amp;rel=0&amp;autoplay=0" frameborder="0" allowfullscreen="" allow="autoplay">
    </iframe>
        </div>
    </div>
    <div class="carousel-inner h-100">
        <div class="carousel-item h-100 item-2" id="no-video" data-interval="5000">
             <img src="/images/image.png" />
        </div>
    </div> 
</div>  

当我使用 onClick 事件或击键事件时,它确实有效。但这显然不是我需要的。

【问题讨论】:

    标签: javascript html jquery bootstrap-4


    【解决方案1】:

    试试这个代码

    <script type="text/javascript">
        $( document ).ready(function() {
            console.log( "document loaded" ); // added for testing
            if ($("iframe").parent().hasClass('active')) {
                console.log( "video loaded" ); // added for testing
                $("#ytplayer-1")[0].src += "&autoplay=1"; // You can refactor this line
            } else {
                $("#ytplayer-1")[0].src += "&autoplay=0";
            }          
        });
    </script>
    

    【讨论】:

    • 不幸的是,这段代码对我不起作用。 hasClass 仍然没有检测到活动的 div
    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2020-05-11
    • 2018-07-27
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多