jQuery 如何跳转到 Bootstrap 的 Carousel 中的特定项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14644929/
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-26 13:48:43  来源:igfitidea点击:

How to jump to a specific item in Bootstrap's Carousel?

jquerytwitter-bootstrapcarousel

提问by Elijah Yang

Using Bootstrap's Carousel, I want to be able to click on a link and jump to a specific slide in the carousel. How do I do that? What jquery do I have to add?

使用 Bootstrap 的 Carousel,我希望能够单击链接并跳转到 carousel 中的特定幻灯片。我怎么做?我必须添加什么 jquery?

Here's my html (it doesn't work but gives you a sense of what I want to do):

这是我的 html(它不起作用,但让您了解我想要做什么):

<a href="#panel">Panel</a>

<div id="myCarousel" class="carousel slide">
 <div class="carousel-inner">
  <div id="panel" class="item">
...
  </div>
 </div>
</div>

回答by David Fregoli

if your links are in the same order of the panels you can do something like:

如果您的链接与面板的顺序相同,您可以执行以下操作:

$('.link').on('click', function() {
    $('#carousel').carousel($(this).index());
});

if you just have a single link just hardcode it:

如果您只有一个链接,只需对其进行硬编码:

var i = 2; //index of the panel    
$('#link').on('click', function() {
    $('#carousel').carousel(i);
});

from the docs:

从文档:

Methods:

carousel(options)

Initializes the carousel with an optional options object and starts cycling through items.

$('.carousel').carousel({
  interval: 2000
})
.carousel('cycle')

Cycles through the carousel items from left to right.

.carousel('pause')

Stops the carousel from cycling through items.

.carousel(number)

Cycles the carousel to a particular frame (0 based, similar to an array).

.carousel('prev')

Cycles to the previous item.

.carousel('next')

Cycles to the next item.

回答by Sujeev

for me the specified scripted method did not work, however based on another example I was able to make it work using data tags

对我来说,指定的脚本方法不起作用,但是基于另一个示例,我能够使用数据标签使其工作

<a data-target="#myCarousel" data-slide-to="0" href="#">First</a>

Please note that data-slide-toindex is based on 0, and this was tested on Bootstrap 4

请注意,data-slide-to索引基于 0,这是在 Bootstrap 4 上测试过的