首页 > 解决方案 > bootstrap 5 carousel 仅在第一次单击下一步后才开始自动滑动

问题描述

我使用 javascript 定义了一个 bootstrap 5 轮播。

当我从浏览器中获取纯生成的 html 时,它工作正常。当我使用 java 脚本生成 html 时,默认情况下不会开始旋转。只有在我单击下一个或上一个箭头手动旋转幻灯片后,它才开始旋转。想法为什么?

下面的代码应该在每次复制和粘贴时都可以在小提琴等中使用。

<head>
  <meta charset="UTF-8">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="fontawesome\css\all.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
  
    class FeaturedContentComponent {
      
      constructor(componentId) {
        this.componentId = componentId;
        this.service_data;
        this.carouselId = componentId + "_carousel"
        this.carouselContentId = componentId + "_carousel_content";
        this.carouselIndicatorId = componentId + "_carousel_inidcators";
      }

      render_component(){
        // create the static layout
        this.make_layout();
        
        var self = this;
        // mock service used
        $.ajax({
          url: "https://jsonplaceholder.typicode.com/todos/1",
          method: 'GET',
          success: function(data, status){   
          //mock data
            self.service_data = [
                                  {
                                    "link": "https://example.com",
                                    "description": "Description A",
                                    "headline": "Headline A"
                                  },
                                  {
                                    "link": "https://example.com",
                                    "description": "Description B",
                                    "headline": "Headline B"
                                  },
                                  {
                                    "link": "https://example.com",
                                    "description": "Description C",
                                    "headline": "Headline C"
                                  },
                                  {
                                    "link": "https://example.com",
                                    "description": "Description D",
                                    "headline": "Headline D"
                                  }
                                ];
            
            var active = " active";
            var indicatorStatus = "class='active' aria-current='true'";
            for (var i = 0; i < self.service_data.length; i++){
              if(i>0){
                active = "";
                indicatorStatus = "";
              }

              let x = "<div class='carousel-item" + active + "'> \
                    <div class='carousel-caption'> \
                      <h3>" + self.service_data[i].headline + "</h3> \
                      <p>" + self.service_data[i].description + "</p> \
                      <a class='btn btn-primary btn-sm' href='" + self.service_data[i].link  + "' role='button' target='_blank'>Take a look &nbsp;&nbsp;<i class='fas fa-external-link-alt'></i></a> \
                    </div> \
                  </div>";
              $("#" + self.carouselContentId).append(x);
              let y = "<button type='button' data-bs-target='#" + self.carouselId + "' data-bs-slide-to='"+ i + "'" + indicatorStatus +  "aria-label='Slide 1'></button>"
              $("#" + self.carouselIndicatorId).append(y);
            }
          }
        });
      }
      make_layout(){
        let static_html = "\
            <div> \
              <div> \
                <style> \
                  #" + this.carouselId + "{ \
                    background-color: #000; \
                  } \
                  .carousel{ \
                    margin-top: 1px; \
                  } \
                  .carousel-inner{ \
                    height: 200px; \
                  } \
                  .carousel-caption{ \
                    color: #fff; \
                    top: 50%; \
                  } \
                </style> \
                <div> \
                  <div id='"+ this.carouselId + "' class='carousel slide' data-bs-ride='carousel'> \
                    <div id='" + this.carouselIndicatorId + "' class='carousel-indicators'></div> \
                    <div id='" + this.carouselContentId + "' class='carousel-inner'></div> \
                    <a class='carousel-control-prev' href='#"+ this.carouselId + "' role='button' data-bs-slide='prev'> \
                      <span class='carousel-control-prev-icon' aria-hidden='true'></span> \
                      <span class='visually-hidden'>Previous</span> \
                    </a> \
                    <a id='test' class='carousel-control-next' href='#"+ this.carouselId + "' role='button' data-bs-slide='next'> \
                      <span class='carousel-control-next-icon' aria-hidden='true'></span> \
                      <span class='visually-hidden'>Next</span> \
                    </a> \
                  </div> \
                </div> \
              </div> \
            </div> \
        ";
        $('#' + this.componentId).append(static_html);

      }  
    }
    
    var fcc = new FeaturedContentComponent('featured');
    
    $(document).ready(function() {
      
      fcc.render_component();

    });
  </script>
</head>
<body class="m-5">  
  <div id='featured'></div>
</body>

标签: bootstrap-5

解决方案


data-bs-*bootstrap.js在加载时根据属性初始化元素。这就是为什么包含它的正确位置是</body>在所有内容加载后的结束标记之前。(https://getbootstrap.com/docs/5.0/getting-started/introduction/#js

在页面加载后添加 BS 元素时,必须手动初始化 JavaScript 行为。(https://getbootstrap.com/docs/5.0/components/carousel/#usage

因此,您需要在对象中使用另一种方法来初始化并开始循环轮播。

<head>
  <meta charset="UTF-8">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

  <link rel="stylesheet" href="fontawesome\css\all.css">
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    class FeaturedContentComponent {

      constructor(componentId) {
        this.componentId = componentId;
        this.service_data;
        this.carouselId = componentId + "_carousel"
        this.carouselContentId = componentId + "_carousel_content";
        this.carouselIndicatorId = componentId + "_carousel_inidcators";
      }

      render_component() {
        // create the static layout
        this.make_layout();

        var self = this;
        // mock service used
        $.ajax({
          url: "https://jsonplaceholder.typicode.com/todos/1",
          method: 'GET',
          success: function(data, status) {
            //mock data
            self.service_data = [{
                "link": "https://example.com",
                "description": "Description A",
                "headline": "Headline A"
              },
              {
                "link": "https://example.com",
                "description": "Description B",
                "headline": "Headline B"
              },
              {
                "link": "https://example.com",
                "description": "Description C",
                "headline": "Headline C"
              },
              {
                "link": "https://example.com",
                "description": "Description D",
                "headline": "Headline D"
              }
            ];

            var active = " active";
            var indicatorStatus = "class='active' aria-current='true'";
            for (var i = 0; i < self.service_data.length; i++) {
              if (i > 0) {
                active = "";
                indicatorStatus = "";
              }

              let x = "<div class='carousel-item" + active + "'> \
                    <div class='carousel-caption'> \
                      <h3>" + self.service_data[i].headline + "</h3> \
                      <p>" + self.service_data[i].description + "</p> \
                      <a class='btn btn-primary btn-sm' href='" + self.service_data[i].link + "' role='button' target='_blank'>Take a look &nbsp;&nbsp;<i class='fas fa-external-link-alt'></i></a> \
                    </div> \
                  </div>";
              $("#" + self.carouselContentId).append(x);
              let y = "<button type='button' data-bs-target='#" + self.carouselId + "' data-bs-slide-to='" + i + "'" + indicatorStatus + "aria-label='Slide 1'></button>"
              $("#" + self.carouselIndicatorId).append(y);
            }
          }
        });
      }
      make_layout() {
        let static_html = "\
            <div> \
              <div> \
                <style> \
                  #" + this.carouselId + "{ \
                    background-color: #000; \
                  } \
                  .carousel{ \
                    margin-top: 1px; \
                  } \
                  .carousel-inner{ \
                    height: 200px; \
                  } \
                  .carousel-caption{ \
                    color: #fff; \
                    top: 50%; \
                  } \
                </style> \
                <div> \
                  <div id='" + this.carouselId + "' class='carousel slide' data-bs-ride='carousel'> \
                    <div id='" + this.carouselIndicatorId + "' class='carousel-indicators'></div> \
                    <div id='" + this.carouselContentId + "' class='carousel-inner'></div> \
                    <a class='carousel-control-prev' href='#" + this.carouselId + "' role='button' data-bs-slide='prev'> \
                      <span class='carousel-control-prev-icon' aria-hidden='true'></span> \
                      <span class='visually-hidden'>Previous</span> \
                    </a> \
                    <a id='test' class='carousel-control-next' href='#" + this.carouselId + "' role='button' data-bs-slide='next'> \
                      <span class='carousel-control-next-icon' aria-hidden='true'></span> \
                      <span class='visually-hidden'>Next</span> \
                    </a> \
                  </div> \
                </div> \
              </div> \
            </div> \
        ";
        $('#' + this.componentId).append(static_html);

      }
      init_carousel() {
        // select the element
        let myCarousel = document.querySelector('#' + this.carouselId)
        // initialize Carousel
        let carousel = new bootstrap.Carousel(myCarousel)
        // start animation
        carousel.cycle()
      }
    }

    var fcc = new FeaturedContentComponent('featured');

    $(document).ready(function() {

      fcc.render_component();
      fcc.init_carousel();

    });
  </script>
</head>

<body class="m-5">
  <div id='featured'></div>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>


推荐阅读