Bootstrap实现轮播图(简便方法)

Bootstrap4官网
轮播图源代码:

<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active">li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1">li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2">li>
  ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="..." class="d-block w-100" alt="...">
    div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    div>
  div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true">span>
    <span class="sr-only">Previousspan>
  a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true">span>
    <span class="sr-only">Nextspan>
  a>
div>

这样复制粘贴固然快捷,但图片较多时容易造成代码冗余,影响可读性。观察可知,其中不少代码相似度较高,所以我们可以通过js动态添加图片

不算简洁的代码:


<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Documenttitle>
	<title>轮播图title>
	
	<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
	<script type="text/javascript" src="jquery.js">script>
	style>
head>
<body>
	
	<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
		<ol class="carousel-indicators">
		ol>
		<div class="carousel-inner">
		div>
		<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
			<span class="carousel-control-prev-icon" aria-hidden="true">span>
			<span class="sr-only">Previousspan>
		a>
		<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
			<span class="carousel-control-next-icon" aria-hidden="true">span>
			<span class="sr-only">Nextspan>
		a>
	div>
body>
<script type="text/javascript">
		var n=12; //n为所需添加的图片数量
		for(var i=0; i<n; ++i)
		{
			$('.carousel-indicators')
			.append('
  • +i+'"'+(i==0?' class="active"':'')+'>
  • '
    ); } for(var i=1; i<=n; ++i) { $('.carousel-inner') .append('') }
    script> <script type="text/javascript" src="bootstrap/js/bootstrap.min.js">script> html> html>

    如果要添加captions说明文字,可以通过数组存储文字内容,在js内添加

    你可能感兴趣的:(Bootstrap实现轮播图(简便方法))