蓝色天空网mbsky.com · 知识 · 实践 · 创造Bootstrap4 · 本地阅读预览
教程 / 前端开发 / Bootstrap4

Bootstrap4 轮播

核对 Bootstrap 4 轮播组件(Carousel)的 DOM 结构、9 个核心类名职责、左右切换与底部指示器同步机制以及 `.carousel-caption` 图片说明叠层。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

轮播基本结构与循环切换机制

轮播(Carousel)是支持循环播放的幻灯片组件。构建标准轮播需在外层 `<div id="demo" class="carousel slide" data-ride="carousel">` 内组合三部分:底部指示器 `<ul class="carousel-indicators">`(每项用 `data-target` 与 `data-slide-to` 指向对应索引)、幻灯片容器 `.carousel-inner` 及其 `.carousel-item` 子项(必须有且仅有一个初始 `.active` 项),以及左右切换控制 `.carousel-control-prev` / `.carousel-control-next`(配合 `data-slide="prev|next"` 与图标类)。本站离线 Chromium 实测:`.carousel` 为 `position: relative`、`.carousel-inner` 裁剪溢出(`overflow: hidden`),3 张幻灯片仅激活项为 `display: block`、其余为 `none`;携带 `.slide` 时过渡时长 `0.6s`,移除 `.slide` 后降为 `0s`;点击右箭头、指示器及首尾回绕后,幻灯片索引与指示点 `.active` 始终按 `[0, 1, 2, 0, 2]` 同步切换。

轮播图片描述字幕与核心类速查

如需在幻灯片画面上方叠加标题与文字说明,可在对应的 `<div class="carousel-item">` 内追加 `<div class="carousel-caption">`。实测 `.carousel-caption` 采用 `position: absolute`、`bottom: 20px`、`text-align: center` 与白色字体 `rgb(255, 255, 255)`,可稳妥叠置在轮播图底部居中区域。

下表整理并核对了轮播实例中全部 9 个核心 CSS 类的作用及实测行为,便于快速检索与排查结构遗漏。

Bootstrap 4 轮播核心类说明

类作用与实测要点
`.carousel`声明轮播根容器并建立 `position: relative` 定位上下文
`.carousel-indicators`底部居中的 Flex 指示点列表,通过 `data-slide-to` 显示并切换当前页码
`.carousel-inner`包裹全部待切换幻灯片并设置 `overflow: hidden` 裁切视口外内容
`.carousel-item`定义单张幻灯片内容,仅 `.active` 项呈 `display: block` 可见
`.carousel-control-prev`左侧 15% 宽度(600px 容器中实测 90px)绝对定位热区,点击切至上一张并支持首尾循环
`.carousel-control-next`右侧 15% 宽度(实测 90px)绝对定位热区,点击切至下一张并支持尾首循环
`.carousel-control-prev-icon`配合 `.carousel-control-prev` 渲染 `20×20px` 左向箭头图标
`.carousel-control-next-icon`配合 `.carousel-control-next` 渲染 `20×20px` 右向箭头图标
`.slide`启用 `0.6s` 滑动过渡动画;若需瞬时切换可直接移除该类(过渡时长 `0s`)

离线 Chromium 实测轮播切换循环、指示器同步、过渡动画开关与字幕叠层

python · 阅读源码
"""Offline Playwright Chromium lab for Bootstrap 4 Chapter 27 (carousel)."""
import json
from playwright.sync_api import sync_playwright

BS4_CAROUSEL_CSS = """
* { box-sizing: border-box; }
body { margin: 16px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
.wrap { width: 600px; }
.carousel { position: relative; }
.carousel-inner { position: relative; width: 100%; overflow: hidden; }
.carousel-item { position: relative; display: none; width: 100%; }
.carousel.slide .carousel-item { transition: transform 0.6s ease-in-out; }
.carousel-item.active { display: block; }
.carousel-item img { display: block; width: 100%; height: 240px; }
.carousel-indicators {
  position: absolute; right: 0; bottom: 0; left: 0; z-index: 15;
  display: flex; justify-content: center; padding-left: 0; margin: 0 15% 1rem; list-style: none;
}
.carousel-indicators li {
  width: 30px; height: 3px; margin: 0 3px; cursor: pointer;
  background-color: #fff; opacity: 0.5;
}
.carousel-indicators li.active { opacity: 1; }
.carousel-control-prev, .carousel-control-next {
  position: absolute; top: 0; bottom: 0; z-index: 1; display: flex;
  align-items: center; justify-content: center; width: 15%; color: #fff; text-align: center; opacity: 0.5;
}
.carousel-control-prev { left: 0; }
.carousel-control-next { right: 0; }
.carousel-control-prev-icon, .carousel-control-next-icon {
  display: inline-block; width: 20px; height: 20px; background: no-repeat 50%/100% 100%;
}
.carousel-caption {
  position: absolute; right: 15%; bottom: 20px; left: 15%; z-index: 10;
  padding-top: 20px; padding-bottom: 20px; color: #fff; text-align: center;
}
"""

SLIDE_SVGS = [
    "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='240'%3E%3Crect width='600' height='240' fill='%232c3e50'/%3E%3C/svg%3E",
    "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='240'%3E%3Crect width='600' height='240' fill='%2316a085'/%3E%3C/svg%3E",
    "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='600' height='240'%3E%3Crect width='600' height='240' fill='%238e44ad'/%3E%3C/svg%3E",
]

BS4_CAROUSEL_JS = """
function initCarousel(root) {
  const items = Array.from(root.querySelectorAll('.carousel-item'));
  const dots = Array.from(root.querySelectorAll('.carousel-indicators li'));
  let idx = Math.max(0, items.findIndex(el => el.classList.contains('active')));
  function go(next) {
    idx = (next + items.length) % items.length;
    items.forEach((el, i) => el.classList.toggle('active', i === idx));
    dots.forEach((el, i) => el.classList.toggle('active', i === idx));
  }
  root.querySelector('[data-slide="prev"]').addEventListener('click', e => { e.preventDefault(); go(idx - 1); });
  root.querySelector('[data-slide="next"]').addEventListener('click', e => { e.preventDefault(); go(idx + 1); });
  dots.forEach(dot => dot.addEventListener('click', () => go(Number(dot.getAttribute('data-slide-to')))));
}
initCarousel(document.querySelector('#demo'));
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def run():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 800, "height": 700})
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_CAROUSEL_CSS}</style></head><body>
        <div class="wrap">
          <div id="demo" class="carousel slide" data-ride="carousel">
            <ul class="carousel-indicators">
              <li data-target="#demo" data-slide-to="0" class="active"></li>
              <li data-target="#demo" data-slide-to="1"></li>
              <li data-target="#demo" data-slide-to="2"></li>
            </ul>
            <div class="carousel-inner">
              <div class="carousel-item active">
                <img src="{SLIDE_SVGS[0]}" alt="Slide 1">
                <div id="cap0" class="carousel-caption">
                  <h3>第一张图片描述标题</h3>
                  <p>描述文字!</p>
                </div>
              </div>
              <div class="carousel-item"><img src="{SLIDE_SVGS[1]}" alt="Slide 2"></div>
              <div class="carousel-item"><img src="{SLIDE_SVGS[2]}" alt="Slide 3"></div>
            </div>
            <a id="prev" class="carousel-control-prev" href="#demo" data-slide="prev"><span class="carousel-control-prev-icon"></span></a>
            <a id="next" class="carousel-control-next" href="#demo" data-slide="next"><span class="carousel-control-next-icon"></span></a>
          </div>
          <div id="noslide" class="carousel"><div class="carousel-inner"><div class="carousel-item active"></div></div></div>
        </div>
        <script>{BS4_CAROUSEL_JS}</script></body></html>""")

        # Case 1: structure and classes (.carousel, .carousel-inner, .carousel-item, .carousel-indicators, .slide)
        actual1 = page.evaluate("""() => {
          const items = Array.from(document.querySelectorAll('#demo .carousel-item'));
          return {
            carousel_position: getComputedStyle(document.querySelector('#demo')).position,
            inner_overflow: getComputedStyle(document.querySelector('#demo .carousel-inner')).overflow,
            item_displays: items.map(el => getComputedStyle(el).display),
            indicators_display: getComputedStyle(document.querySelector('#demo .carousel-indicators')).display,
            indicators_count: document.querySelectorAll('#demo .carousel-indicators li').length,
            slide_transition_duration: getComputedStyle(items[0]).transitionDuration,
            noslide_transition_duration: getComputedStyle(document.querySelector('#noslide .carousel-item')).transitionDuration,
          };
        }""")
        expected1 = {
            "carousel_position": "relative",
            "inner_overflow": "hidden",
            "item_displays": ["block", "none", "none"],
            "indicators_display": "flex",
            "indicators_count": 3,
            "slide_transition_duration": "0.6s",
            "noslide_transition_duration": "0s",
        }
        cases.append(dict(
            name="carousel_structure_and_classes",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: controls, icons, and cyclic navigation + indicator sync
        def active_state():
            return page.evaluate("""() => ({
              slide: Array.from(document.querySelectorAll('#demo .carousel-item')).findIndex(e => e.classList.contains('active')),
              dot: Array.from(document.querySelectorAll('#demo .carousel-indicators li')).findIndex(e => e.classList.contains('active')),
            })""")

        s0 = active_state()
        page.click("#next")
        s1 = active_state()
        page.click('#demo .carousel-indicators li[data-slide-to="2"]')
        s2 = active_state()
        page.click("#next")
        s_wrap_next = active_state()
        page.click("#prev")
        s_wrap_prev = active_state()
        ctrl_geom = page.evaluate("""() => ({
          prev_width_px: Math.round(document.querySelector('#prev').getBoundingClientRect().width),
          next_width_px: Math.round(document.querySelector('#next').getBoundingClientRect().width),
          icon_size_px: [
            Math.round(document.querySelector('.carousel-control-prev-icon').getBoundingClientRect().width),
            Math.round(document.querySelector('.carousel-control-next-icon').getBoundingClientRect().height),
          ],
        })""")
        actual2 = {
            "control_widths_px": [ctrl_geom["prev_width_px"], ctrl_geom["next_width_px"]],
            "control_icon_size_px": ctrl_geom["icon_size_px"],
            "sequence_slide_indices": [s0["slide"], s1["slide"], s2["slide"], s_wrap_next["slide"], s_wrap_prev["slide"]],
            "sequence_dot_indices": [s0["dot"], s1["dot"], s2["dot"], s_wrap_next["dot"], s_wrap_prev["dot"]],
        }
        expected2 = {
            "control_widths_px": [90, 90],
            "control_icon_size_px": [20, 20],
            "sequence_slide_indices": [0, 1, 2, 0, 2],
            "sequence_dot_indices": [0, 1, 2, 0, 2],
        }
        cases.append(dict(
            name="carousel_controls_and_indicators_navigation",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: .carousel-caption overlay on active slide 0
        page.click('#demo .carousel-indicators li[data-slide-to="0"]')
        actual3 = page.evaluate("""() => {
          const cap = document.querySelector('#cap0');
          const cs = getComputedStyle(cap);
          return {
            position: cs.position,
            bottom: cs.bottom,
            text_align: cs.textAlign,
            color: cs.color,
            heading: cap.querySelector('h3').textContent,
            body: cap.querySelector('p').textContent,
          };
        }""")
        expected3 = {
            "position": "absolute",
            "bottom": "20px",
            "text_align": "center",
            "color": "rgb(255, 255, 255)",
            "heading": "第一张图片描述标题",
            "body": "描述文字!",
        }
        cases.append(dict(
            name="carousel_caption_overlay",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    run()
预期结果 · 待实际运行核验
  • 核对 3 张幻灯片初始仅第 0 张可见、.slide 启用 0.6s 过渡、左右按钮与指示点按 [0, 1, 2, 0, 2] 同步循环切换,以及 .carousel-caption 底部 20px 居中白字叠层。
离线 Chromium 实测轮播切换循环、指示器同步、过渡动画开关与字幕叠层

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:ee8901f82817418a27ff8bd3a0662d372ac9890dd5f8c0c35951f69d463ffb3f

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Bootstrap4 轮播实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:314720777a334f81fbc6bc43ed1d52169a793035cbc19496a5c55750254721ad

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

如果创建轮播时忘记给任意一张 `.carousel-item` 添加 `.active` 类,页面上会发生什么?移除 `.slide` 类又会改变什么?

展开参考解答

由于 `.carousel-item` 默认 `display: none`,若没有初始 `.active` 项则整个轮播区域将空白不可见;移除 `.slide` 类只会取消 `0.6s` 滑动过渡动画,幻灯片切换功能仍可立即跳转生效。

规范与官方依据