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

jEasyUI 设置冻结列

核对 DataGrid 的 frozenColumns 配置与声明式 <thead frozen="true"> 写法,以及横向滚动时冻结列保持视口固定不滚出的离线 Chromium 几何实测。

学完这一章,你能够

  • 核对 DataGrid 的 frozenColumns 配置与声明式 <thead frozen="true"> 写法,以及横向滚动时冻结列保持视口固定不滚出的离线 Chromium 几何实测。

通过 frozenColumns 与声明式 thead 冻结关键列

当数据网格列数较多需要横向拖动滚动条查看右侧明细时,常需将左侧编号、名称等关键列固定在视口内。在 JavaScript 初始化配置中,只需定义与 `columns` 结构相同的二维数组 `frozenColumns`(如冻结 `itemid` 与 `productid` 两列),右侧滚动列仍放在 `columns` 中。

如果不写 JavaScript,也可直接在 HTML 表格中使用两个 `<thead>`:为需要固定的列组加上 `<thead frozen="true">`,其余可滚动列放在普通 `<thead>` 中即可。本站 Chromium 离线实测核验:冻结列 `itemid`(`left: 0px`)与 `productid`(`left: 80px`)采用 `position: sticky` 固定,将 `500px` 滚动视口向右滚动 `180px` 后,两个冻结列的视口左坐标偏移量精确为 `0px`,而普通列 `listprice` 向左平移 `-180px`;同时声明式 `<thead frozen="true">` 解析出的冻结列与普通列清单与 JS 配置完全一致。

参考示例包 `jeasyui-datagrid-datagrid5.zip` 遵循来源站访问停止状态未联网下载并已登记于附件清单;运行离线实验脚本可直观复现横向滚动坐标差与声明式解析结果。

运行 DataGrid 冻结列横向滚动定位与声明式解析的离线 Chromium 实验

含完整源码 · 227 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 26: Frozen Columns."""
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 Frozen Columns Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { width: 500px; border: 1px solid #95b8e7; box-sizing: border-box; margin-bottom: 16px; }
  .dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
  .datagrid-scroll { width: 500px; height: 180px; overflow-x: auto; overflow-y: auto; position: relative; }
  table.dg-frozen-tbl { border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12px; }
  table.dg-frozen-tbl th, table.dg-frozen-tbl td {
    border-right: 1px solid #ccc; border-bottom: 1px solid #ccc;
    padding: 4px 6px; box-sizing: border-box; background: #fff; white-space: nowrap;
  }
  table.dg-frozen-tbl th { background: #efefef; }
  table.dg-frozen-tbl .frozen-col { position: sticky; z-index: 2; background: #f8fbff; }
  table.dg-frozen-tbl th.frozen-col { z-index: 3; background: #e6eefb; }
</style>
</head>
<body>
<div id="js-grid-host"></div>

<table id="decl-tt" title="Frozen Columns" class="easyui-datagrid" style="width:500px;height:250px"
       singleSelect="true" iconCls="icon-save">
  <thead frozen="true">
    <tr>
      <th field="itemid" width="80">Item ID</th>
      <th field="productid" width="80">Product ID</th>
    </tr>
  </thead>
  <thead>
    <tr>
      <th field="listprice" width="80" align="right">List Price</th>
      <th field="unitcost" width="80" align="right">Unit Cost</th>
      <th field="attr1" width="150">Attribute</th>
      <th field="status" width="60" align="center">Status</th>
    </tr>
  </thead>
</table>

<script>
const ROWS = [
  { itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large Adult Male Tropical Fish", status: "P" },
  { itemid: "EST-10", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted Adult Female Dalmatian", status: "P" },
  { itemid: "EST-11", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Venomless Desert Rattlesnake", status: "P" },
];

function buildFrozenGrid(hostEl, cfg) {
  const panel = document.createElement('div');
  panel.className = 'dg-panel';
  panel.innerHTML = `<div class="dg-title">${cfg.title}</div><div class="datagrid-scroll" id="scroll-box"></div>`;
  const scrollBox = panel.querySelector('#scroll-box');
  const frozen = cfg.frozenColumns[0];
  const normal = cfg.columns[0];
  const allCols = [...frozen.map(c => ({ ...c, frozen: true })), ...normal.map(c => ({ ...c, frozen: false }))];

  let leftOffset = 0;
  allCols.forEach(c => {
    if (c.frozen) {
      c.stickyLeft = leftOffset;
      leftOffset += c.width;
    }
  });
  const totalWidth = allCols.reduce((s, c) => s + c.width, 0);

  const tbl = document.createElement('table');
  tbl.className = 'dg-frozen-tbl';
  tbl.style.width = totalWidth + 'px';
  const thead = document.createElement('thead');
  const htr = document.createElement('tr');
  allCols.forEach(c => {
    const th = document.createElement('th');
    th.dataset.field = c.field;
    th.style.width = c.width + 'px';
    th.style.minWidth = c.width + 'px';
    th.textContent = c.title;
    if (c.frozen) {
      th.className = 'frozen-col';
      th.style.left = c.stickyLeft + 'px';
    }
    htr.appendChild(th);
  });
  thead.appendChild(htr);
  tbl.appendChild(thead);

  const tbody = document.createElement('tbody');
  ROWS.forEach(r => {
    const tr = document.createElement('tr');
    allCols.forEach(c => {
      const td = document.createElement('td');
      td.dataset.field = c.field;
      td.style.width = c.width + 'px';
      td.style.minWidth = c.width + 'px';
      if (c.align) td.style.textAlign = c.align;
      td.textContent = r[c.field];
      if (c.frozen) {
        td.className = 'frozen-col';
        td.style.left = c.stickyLeft + 'px';
      }
      tr.appendChild(td);
    });
    tbody.appendChild(tr);
  });
  tbl.appendChild(tbody);
  scrollBox.appendChild(tbl);
  hostEl.appendChild(panel);
}

buildFrozenGrid(document.getElementById('js-grid-host'), {
  title: 'Frozen Columns',
  width: 500,
  height: 250,
  frozenColumns: [[
    { field: 'itemid', title: 'Item ID', width: 80 },
    { field: 'productid', title: 'Product ID', width: 80 },
  ]],
  columns: [[
    { field: 'listprice', title: 'List Price', width: 120, align: 'right' },
    { field: 'unitcost', title: 'Unit Cost', width: 120, align: 'right' },
    { field: 'attr1', title: 'Attribute', width: 240 },
    { field: 'status', title: 'Status', width: 100 },
  ]]
});

window.parseDeclarativeFrozen = function() {
  const tbl = document.getElementById('decl-tt');
  const frozenThead = tbl.querySelector('thead[frozen="true"]');
  const normalThead = tbl.querySelector('thead:not([frozen="true"])');
  return {
    title: tbl.getAttribute('title'),
    singleSelect: tbl.getAttribute('singleSelect') === 'true',
    frozenFields: Array.from(frozenThead.querySelectorAll('th')).map(th => th.getAttribute('field')),
    normalFields: Array.from(normalThead.querySelectorAll('th')).map(th => th.getAttribute('field')),
  };
};
</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": 700, "height": 500})
        page.set_content(HTML_DOC)

        # Case 1: JS frozenColumns sticky configuration
        res1 = page.evaluate("""() => {
            const c0 = getComputedStyle(document.querySelector('th[data-field="itemid"]'));
            const c1 = getComputedStyle(document.querySelector('th[data-field="productid"]'));
            const c2 = getComputedStyle(document.querySelector('th[data-field="listprice"]'));
            const box = document.getElementById('scroll-box');
            return {
                itemidPosition: c0.position,
                itemidLeft: c0.left,
                productidPosition: c1.position,
                productidLeft: c1.left,
                listpricePosition: c2.position,
                canScrollHorizontally: box.scrollWidth > box.clientWidth,
            };
        }""")
        exp1 = {
            "itemidPosition": "sticky",
            "itemidLeft": "0px",
            "productidPosition": "sticky",
            "productidLeft": "80px",
            "listpricePosition": "static",
            "canScrollHorizontally": True,
        }
        cases.append(dict(name="js_frozen_columns_config_and_sticky", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Horizontal scroll keeps frozen cells pinned while normal columns scroll
        res2 = page.evaluate("""() => {
            const box = document.getElementById('scroll-box');
            const beforeItem = document.querySelector('tbody td[data-field="itemid"]').getBoundingClientRect().left;
            const beforeProd = document.querySelector('tbody td[data-field="productid"]').getBoundingClientRect().left;
            const beforePrice = document.querySelector('tbody td[data-field="listprice"]').getBoundingClientRect().left;
            box.scrollLeft = 180;
            const afterItem = document.querySelector('tbody td[data-field="itemid"]').getBoundingClientRect().left;
            const afterProd = document.querySelector('tbody td[data-field="productid"]').getBoundingClientRect().left;
            const afterPrice = document.querySelector('tbody td[data-field="listprice"]').getBoundingClientRect().left;
            return {
                scrollLeft: box.scrollLeft,
                itemidDelta: Math.round(afterItem - beforeItem),
                productidDelta: Math.round(afterProd - beforeProd),
                listpriceDelta: Math.round(afterPrice - beforePrice),
            };
        }""")
        exp2 = {
            "scrollLeft": 180,
            "itemidDelta": 0,
            "productidDelta": 0,
            "listpriceDelta": -180,
        }
        cases.append(dict(name="horizontal_scroll_keeps_frozen_in_viewport", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Declarative <thead frozen="true"> equivalence
        res3 = page.evaluate("() => window.parseDeclarativeFrozen()")
        exp3 = {
            "title": "Frozen Columns",
            "singleSelect": True,
            "frozenFields": ["itemid", "productid"],
            "normalFields": ["listprice", "unitcost", "attr1", "status"],
        }
        cases.append(dict(name="declarative_thead_frozen_true_equivalence", expected=exp3, actual=res3, passed=(res3 == exp3)))

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


if __name__ == "__main__":
    main()
核对 frozenColumns 左偏移(0px/80px)、横向滚动 180px 时冻结列位移 0px 而普通列位移 -180px,以及 <thead frozen="true"> 等价解析。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

冻结列宽度固定且不会随滚动区域收缩;若冻结列总宽接近或超过表格容器宽度,会导致右侧可滚动区域过窄甚至无法正常显示,因此在宽表场景下通常关闭 `fitColumns` 并仅冻结 1~2 个核心标识列。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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