蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery EasyUI 教程目录 68章
课程介绍
jQuery EasyUI / LEARN BY DOING

jEasyUI 添加自动播放标签页

核对 Tabs 的 tabs 方法读取面板集合、panel('options').title 取标题,以及通过 setInterval 驱动标签页循环轮播与停止控制的离线实测。

学完这一章,你能够

  • 核对 Tabs 的 tabs 方法读取面板集合、panel('options').title 取标题,以及通过 setInterval 驱动标签页循环轮播与停止控制的离线实测。

自动播放标签页的应用与容器准备

自动播放(Autoplay)标签页常见于商品橱窗或轮播展示区:Tabs 按顺序展示第 1、第 2、第 3 个面板,到达末尾后再折返首项形成持续循环。

第一步在 HTML 中创建 `id="tt"`、`class="easyui-tabs"`、尺寸为 `330px × 270px` 的容器,内部放置 `Shirt1` 至 `Shirt5` 共 5 个 `padding:20px` 子面板及对应展示图。本站离线实验以 80×80 内联 SVG 占位图替代外部 GIF,Chromium 实测容器宽高精确为 `330 × 270` 像素、面板数为 5、首项默认激活 `Shirt1` 且内边距为 `20px`。

定时轮播逻辑与循环边界核验

第二步实现轮播脚本:调用 `t.tabs('tabs')` 获取全部面板数组,配合 `setInterval(..., 3000)` 每次读取 `tabs[index].panel('options').title` 并传入 `t.tabs('select', title)` 激活,同时递增 `index` 并在 `index >= tabs.length` 时归零。本站 Chromium 离线实测连续驱动 7 个周期(实验内缩短间隔以保证快速确定性),选中序列严格输出 `['Shirt1', 'Shirt2', 'Shirt3', 'Shirt4', 'Shirt5', 'Shirt1', 'Shirt2']`,任意时刻仅 1 个面板处于可见状态,调用 `clearInterval` 后选中项稳定停留在 `Shirt2`。

原始示例压缩包 `jeasyui-layout-tabs3.zip` 未发起外网下载并已登记于附件清单;通过本地离线 Chromium 实验脚本可直接复现全部 5 面板轮播、折返与暂停行为。

运行五面板自动轮播与循环折返的离线 Chromium 实验

含完整源码 · 176 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 19: Autoplay Tabs."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI Autoplay Tabs Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .easyui-tabs { border: 1px solid #95b8e7; display: flex; flex-direction: column; box-sizing: border-box; }
  .tabs-header { display: flex; background: #e0ecff; border-bottom: 1px solid #95b8e7; padding: 4px 4px 0; gap: 3px; }
  .tabs-tab { padding: 4px 8px; border: 1px solid #95b8e7; border-bottom: none; background: #f4f8ff; font-size: 12px; cursor: pointer; }
  .tabs-tab.tabs-selected { background: #fff; font-weight: 600; }
  .tabs-panels { flex: 1; }
  .tabs-panel { display: none; padding: 20px; box-sizing: border-box; }
  .tabs-panel.active { display: block; }
</style>
</head>
<body>
<div id="tt" class="easyui-tabs" style="width:330px;height:270px;">
  <div title="Shirt1" style="padding:20px;"><img alt="Shirt1" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Crect width='80' height='80' fill='%23dbeafe'/%3E%3Ctext x='14' y='45' font-size='14'%3EShirt1%3C/text%3E%3C/svg%3E"></div>
  <div title="Shirt2" style="padding:20px;"><img alt="Shirt2" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Crect width='80' height='80' fill='%23fce7f3'/%3E%3Ctext x='14' y='45' font-size='14'%3EShirt2%3C/text%3E%3C/svg%3E"></div>
  <div title="Shirt3" style="padding:20px;"><img alt="Shirt3" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Crect width='80' height='80' fill='%23dcfce7'/%3E%3Ctext x='14' y='45' font-size='14'%3EShirt3%3C/text%3E%3C/svg%3E"></div>
  <div title="Shirt4" style="padding:20px;"><img alt="Shirt4" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Crect width='80' height='80' fill='%23fef3c7'/%3E%3Ctext x='14' y='45' font-size='14'%3EShirt4%3C/text%3E%3C/svg%3E"></div>
  <div title="Shirt5" style="padding:20px;"><img alt="Shirt5" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='80' height='80'%3E%3Crect width='80' height='80' fill='%23ede9fe'/%3E%3Ctext x='14' y='45' font-size='14'%3EShirt5%3C/text%3E%3C/svg%3E"></div>
</div>
<script>
(function(){
  const container = document.getElementById('tt');
  const rawPanels = Array.from(container.children);
  container.innerHTML = '<div class="tabs-header"></div><div class="tabs-panels"></div>';
  const header = container.querySelector('.tabs-header');
  const panelsEl = container.querySelector('.tabs-panels');
  const tabs = [];
  let selected = null;

  function selectTab(title) {
    selected = title;
    tabs.forEach(item => {
      const active = item.options.title === title;
      item.tabEl.classList.toggle('tabs-selected', active);
      item.panelEl.classList.toggle('active', active);
    });
  }

  rawPanels.forEach(div => {
    const title = div.getAttribute('title');
    const tabEl = document.createElement('div');
    tabEl.className = 'tabs-tab';
    tabEl.textContent = title;
    tabEl.addEventListener('click', () => selectTab(title));
    const panelEl = document.createElement('div');
    panelEl.className = 'tabs-panel';
    panelEl.dataset.title = title;
    panelEl.innerHTML = div.innerHTML;
    header.appendChild(tabEl);
    panelsEl.appendChild(panelEl);
    tabs.push({
      options: { title },
      tabEl,
      panelEl,
      panel(cmd) { return cmd === 'options' ? this.options : null; }
    });
  });
  selectTab(tabs[0].options.title);

  window.tabsWidget = {
    tabs() { return tabs; },
    select(title) { selectTab(title); },
    getSelected() { return selected; },
    visibleTitles() {
      return tabs.filter(t => getComputedStyle(t.panelEl).display !== 'none').map(t => t.options.title);
    }
  };

  window.runAutoplay = function(intervalMs, maxTicks) {
    return new Promise(resolve => {
      let index = 0;
      const allTabs = window.tabsWidget.tabs();
      const history = [];
      const timerId = setInterval(() => {
        const title = allTabs[index].panel('options').title;
        window.tabsWidget.select(title);
        history.push(window.tabsWidget.getSelected());
        index++;
        if (index >= allTabs.length) {
          index = 0;
        }
        if (history.length >= maxTicks) {
          clearInterval(timerId);
          window._lastTimerStopped = true;
          resolve({ history, finalIndex: index, finalSelected: window.tabsWidget.getSelected() });
        }
      }, intervalMs);
    });
  };
})();
</script>
</body>
</html>
"""


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


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 600, "height": 420})
        page.set_content(HTML_DOC)

        # Case 1: Initial 5 Shirt tabs and container dimensions
        res1 = page.evaluate("""() => {
            const box = document.getElementById('tt').getBoundingClientRect();
            const titles = window.tabsWidget.tabs().map(t => t.panel('options').title);
            const firstPad = getComputedStyle(document.querySelector('.tabs-panel.active')).padding;
            const imgsLoaded = Array.from(document.querySelectorAll('.tabs-panel img')).every(img => img.complete && img.naturalWidth === 80);
            return {
                width: Math.round(box.width),
                height: Math.round(box.height),
                count: titles.length,
                titles,
                initialSelected: window.tabsWidget.getSelected(),
                firstPanelPadding: firstPad,
                imgsLoaded,
            };
        }""")
        exp1 = {
            "width": 330,
            "height": 270,
            "count": 5,
            "titles": ["Shirt1", "Shirt2", "Shirt3", "Shirt4", "Shirt5"],
            "initialSelected": "Shirt1",
            "firstPanelPadding": "20px",
            "imgsLoaded": True,
        }
        cases.append(dict(name="initial_five_shirt_tabs", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: setInterval autoplay cycles through all 5 tabs and wraps to Shirt1
        res2 = page.evaluate("() => window.runAutoplay(15, 7)")
        exp2 = {
            "history": ["Shirt1", "Shirt2", "Shirt3", "Shirt4", "Shirt5", "Shirt1", "Shirt2"],
            "finalIndex": 2,
            "finalSelected": "Shirt2",
        }
        cases.append(dict(name="autoplay_interval_cycle_and_wrap", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Single visible panel invariant & stable state after clearInterval
        page.wait_for_timeout(60)
        res3 = page.evaluate("""() => ({
            visibleTitles: window.tabsWidget.visibleTitles(),
            selectedAfterWait: window.tabsWidget.getSelected(),
            timerStopped: Boolean(window._lastTimerStopped),
        })""")
        exp3 = {
            "visibleTitles": ["Shirt2"],
            "selectedAfterWait": "Shirt2",
            "timerStopped": True,
        }
        cases.append(dict(name="active_panel_visibility_and_pause_control", expected=exp3, actual=res3, passed=(res3 == exp3)))

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


if __name__ == "__main__":
    main()
核对 330×270 容器内 5 个 Shirt 面板、7 次定时轮播精确折返至 Shirt1/Shirt2、单面板可见不变式及 clearInterval 停止控制。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a964.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1005.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

直接从 `t.tabs('tabs')` 读取当前全部面板的 `options.title`,即使运行期动态增删或重排标签页,轮播脚本仍能与实际面板集合保持同步。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习