使用 jQuery 动态地将幻灯片添加到 Bootstrap 3 轮播

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24177572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:29:13  来源:igfitidea点击:

Add slides to Bootstrap 3 carousel dynamically using jQuery

jquerytwitter-bootstrap-3slidercarousel

提问by idrisjafer

I'm trying to add slides to Bootstrap carousel using jQuery but it is not acting as a slider in the browser. Instead it's showing the images in list view.

我正在尝试使用 jQuery 将幻灯片添加到 Bootstrap carousel,但它没有充当浏览器中的滑块。相反,它在列表视图中显示图像。

<!DOCTYPE html>
<html>
<head>
<link href="Assets/css/bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">        </script>
<script src="Assets/js/bootstrap.min.js"></script>
<title></title>
<script>
    onload=function(){

        for(var m=3;m>=0;m--)
        {
            var path="file_uploads/"+m+".jpg";
            $(".carousel-indicators").after("<li data-target='#carousel-example-generic' data-slide-to=\""+m+"\"></li>");
            $(".carousel-inner").after("<div class='item'><img src='"+path+"' alt='"+m+"'></div>");             
        }

        $(".carousel-indicators li:first").addClass("active");
        $(".carousel-inner .item:first").addClass("active");
        $('.carousel').carousel();
    }
</script>
</head>
<body>
  <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
    <ol class="carousel-indicators">

    </ol>
    <!-- Wrapper for slides -->
    <div class="carousel-inner">       

    </div>

    <!-- Controls -->
    <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
    </a>
    <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
    </a>
  </div>
</body>
</html> 

回答by avcajaraville

First thing, I will rely on the fact that m is an array with proper url to your images.

首先,我将依赖这样一个事实,即 m 是一个数组,具有正确的图像 url。

The HTML should be like this:

HTML 应该是这样的:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
  <ol class="carousel-indicators"></ol>
  <!-- Wrapper for slides -->
  <div class="carousel-inner"></div>
  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right"></span>
  </a>
</div>

Class carousel inner is empty, there is where you gonna place your images for then carousel.

类轮播内部是空的,您可以在那里放置用于轮播的图像。

Class carousel-indicatiors is also empty, will be filled by JS.

class carousel-indicators 也是空的,会被 JS 填充。

Then, comes the JS: (as I said, Im relying on the fact that m is an array of imgs url)

然后,来了 JS :(正如我所说,我依赖于 m 是一个 imgs url 数组)

$(document).ready(function(){  
  for(var i=0 ; i< m.length ; i++) {
    $('<div class="item"><img src="'+m[i]+'"><div class="carousel-caption"></div>   </div>').appendTo('.carousel-inner');
    $('<li data-target="#carousel-example-generic" data-slide-to="'+i+'"></li>').appendTo('.carousel-indicators')

  }
  $('.item').first().addClass('active');
  $('.carousel-indicators > li').first().addClass('active');
  $('#carousel-example-generic').carousel();
});

Basically, you append all your images to class carousel-inner, you add carousel control li's, then you add the active class to the first image and to the first carousel indicator li., and finally, you initialize your carousel. Note that all this is inside a document ready function, which is what you are missing. What you do is only define a function called onload

基本上,您将所有图像附加到类 carousel-inner,添加轮播控件 li,然后将活动类添加到第一个图像和第一个轮播指示器 li.,最后,初始化您的轮播。请注意,所有这些都在文档就绪函数中,而这正是您所缺少的。你所做的只是定义一个名为 onload 的函数

Hope it helps !

希望能帮助到你 !

EDIT: I saw that you are outputting also alt tag to images, but thats something that not need to be on my answer, I bet you can do that without problems.

编辑:我看到你也在向图像输出 alt 标签,但这不是我的答案,我敢打赌你可以毫无问题地做到这一点。

回答by Rick

You can give this a try.

你可以试试这个。

Markup

标记

<div id="carousel-deck" class="carousel slide" data-ride="carousel"
    data-interval="false" data-wrap="false">
    <ol class="carousel-indicators">
    </ol>
    <div class="carousel-inner">
    </div>
    <a class="left carousel-control" href="#carousel-deck"
        data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span><span
            class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#carousel-deck"
        data-slide="next"><span
            class="glyphicon glyphicon-chevron-right"></span><span
            class="sr-only">Next</span>
    </a>
</div>

JS

JS

var markup = '';
for (var index = 0; index < count; index++) {
    markup += '<li data-target="#carousel-deck" data-slide-to="' + index + '"></li>';
}
$('#carousel-deck .carousel-indicators').html(markup);
markup = '';
for (var index = 0; index < count; index++) {
    markup += '<div class="item">';
    markup += '<img src="/images/uploads/' + file.uuid + '/slides/slide_' + (index + 1) + '.jpg" style="width:100%;">'
    markup += '</div>';
}
$('#carousel-deck .carousel-inner').html(markup);
$('#carousel-deck .item').first().addClass('active');
$('#carousel-deck .carousel-indicators > li').first().addClass('active');
$('#carousel-deck').carousel({
    pause: true,
    interval: false
});

回答by IAM_AL_X

Here is a more current answer. The solution by @avcajaraville was written in 2014; with Bootstrap version 4 the concepts he presented are still applicable but the details regarding Class names have changed and the old code won't work.

这是一个更当前的答案。@avcajaraville 的解决方案写于 2014 年;在 Bootstrap 版本 4 中,他提出的概念仍然适用,但有关类名称的详细信息已更改,旧代码将无法使用。

In this solution, I don't bother with "indicators," the addition of indicators is left to the interested reader. (The "indicators" are symbols representing the list, there is one "dot" per photo in the carousel, and the dot for the current photo is highlighted.)

在这个解决方案中,我不关心“指标”,指标的添加留给感兴趣的读者。(“指标”是代表列表的符号,轮播中每张照片有一个“点”,当前照片的点高亮显示。)

Here is the HTML. This is "bare-bones" version. A more robust version appears later in this post.

这是 HTML。这是“裸机”版本。更强大的版本出现在这篇文章的后面。

<div id="myCarousel" class="carousel slide" >
    <div class="carousel-inner" role="listbox">
    </div> 
</div>

Note that I left out the attribute data-ride="carousel"; the equivalent is expressed in the config options passed via JavaScript. This complies with the latest documentation.

请注意,我省略了属性 data-ride="carousel"; 等效项表示在通过 JavaScript 传递的配置选项中。这符合最新的文档。

Here is the JavaScript. For the sake of variety, this code differs from that of @avcajarville by mostly not using jQuery. On the other hand, the interface to Bootstrap is through jQuery, only, and that is what you see in the last line of this code.

这是 JavaScript。出于多样性的考虑,此代码与@avcajarville 的代码不同,主要是不使用 jQuery。另一方面,Bootstrap 的接口仅通过 jQuery,这就是您在此代码的最后一行中看到的内容。

The presumption is that an array called recsis a list of objects, where each object holds information about the photos, including the file name and some descriptive text. For each rec, a string of html is generated, and pushed onto the array itemHtmlStrings. Those strings then become the innerHTML of carousel-innerelement. Then, one of the new elements (the first one) gets marked as the active(i.e. visible) image.

假设被调用的数组recs是一个对象列表,其中每个对象都保存有关照片的信息,包括文件名和一些描述性文本。对于每个 rec ,生成一个 html 字符串,并将其推送到 array 上itemHtmlStrings。这些字符串然后成为carousel-inner元素的innerHTML 。然后,新元素之一(第一个)被标记为活动(即可见)图像。

var itemHtmlStrings = [];
for(var rec of recs) {
  var itemHtmlString = ''
    +'<div class="carousel-item">'
    + `<img class="d-block w-100" `
    +       ` src="photo/${rec.name}" alt="photo of ${rec.name}">`
    +  `<div class="carousel-caption">`
    +    `<h3>${rec.captionHdr}</h3>`
    +    `<p>${rec.captionText}</p>`
    +  '</div>'
    +'</div>'
  itemHtmlStrings.push(itemHtmlString);
}
var myCarouselEl = document.getElementById("myCarousel");
var carouselInnerEl = myCarouselEl.getElementsByClassName("carousel-inner")[0];
carouselInnerEl.innerHTML = itemHtmlStrings.join("\n");
carouselInnerEl.firstElementChild.className += " active";
$(myCarouselEl).carousel({slide : true, ride : true });

Unfortunately, after writing this code, I decided that the Carousel offered by Bootstrap is not for me. This code is OK if your only requirement is to rotate through an enumerated set of images and show exactly one at a time. I am not using this code because I need to show more than one image, and it seems Bootstrap does not do that. Furthermore, I had problems because my images are not all identical; some needed to be rotated upon load; that was a problem in Bootstrap Carousel. Also, I'm not sure how well it handles diversity of size and aspect ratio.

不幸的是,写完这段代码后,我决定 Bootstrap 提供的 Carousel 不适合我。如果您的唯一要求是旋转一组枚举图像并一次只显示一个,则此代码是可以的。我没有使用此代码,因为我需要显示多个图像,而 Bootstrap 似乎没有这样做。此外,我遇到了问题,因为我的图像并不完全相同;有些需要在负载时旋转;这是 Bootstrap Carousel 中的一个问题。另外,我不确定它处理大小和纵横比的多样性的情况如何。

I promised the non-bare-bones version of the HTML, so here it is. This includes buttons that allow the user to request the Previousand Nextslide. Also, it includes aria-hiddenattributes and sr-onlyspans; these are codes for screen readers. The sr-onlyclass is the Bootstrap indicator of screen-reader-only. (Screen reader is a "voice" for visual impaired people.)

我承诺了 HTML 的非基本版本,所以它在这里。这包括允许用户请求一张下一张幻灯片的按钮。此外,它还包括aria-hidden属性和sr-only跨度;这些是屏幕阅读器的代码。该sr-only班是的引导指标-读者仅屏幕。(屏幕阅读器是视障人士的“声音”。)

<div id="myCarousel" class="carousel slide" >
    <div class="carousel-inner" role="listbox">
    </div>
    <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true" style="background-color:black; color:white;"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true" style="background-color:black; color:white; font-size=x-large"></span>
        <span class="sr-only">Next</span>
    </a>
</div>

To add indicators, put <ol class="carousel-indicators"></ol>prior to the carousel-inner, and adjust the JavaScript code to insert a list of <li>elements. When using indicators, you will need to set "active" on the appropriate (i.e. first) indicator element, as was done by @avcajaraville.

要添加指标,请放在<ol class="carousel-indicators"></ol>之前carousel-inner,然后调整 JavaScript 代码以插入<li>元素列表。使用指标时,您需要在适当的(即第一个)指标元素上设置“活动”,正如@avcajaraville 所做的那样。

Good luck, and have fun.

祝好运并玩得开心点。

回答by Vikash Pandey

Well, Bootstrap Carousel has various parameters to control.

好吧,Bootstrap Carousel 有各种参数需要控制。

i.e.

IE

Interval:Specifies the delay (in milliseconds) between each slide.

间隔:指定每张幻灯片之间的延迟(以毫秒为单位)。

pause:Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.

pause:当鼠标指针进入轮播时暂停轮播通过下一张幻灯片,并在鼠标指针离开轮播时恢复滑动。

wrap:Specifies whether the carousel should go through all slides continuously, or stop at the last slide

wrap:指定轮播是连续遍历所有幻灯片,还是停在最后一张幻灯片

For your reference:

供你参考:

parameters of carousel

轮播参数

Fore more details please click here...

欲知更多详情,请点击这里...

Hope this will help you :)

希望能帮到你 :)

Note:this is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.

注意:这是为了进一步的帮助。我的意思是,一旦加载了轮播,您如何自定义或更改默认行为。