我试图使用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>
解决方法
首先,我将依靠这个事实,即m是一个数组,其中包含适当的URL.
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>
类转盘内部是空的,那里有你要将图像放在那里的地方.
班级旋转木马指数也是空的,将由JS填补.
然后,来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(); });
基本上,您将所有图像附加到类别carousel-inner,您添加旋转木马控制li,然后将活动类添加到第一个图像和第一个轮播指示符li.最后,您初始化您的轮播.请注意,所有这些都在文档就绪功能中,这是您缺少的内容.你所做的只是定义一个名为onload的函数
希望有帮助!