You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中实现嵌套表格展开不改变主表格尺寸的方法

Blazor可展开表格:内部表格超出主表格边框显示的实现方案

当前实现中内部表格会撑开主表格,核心原因是内部表格作为主表格单元格的子元素,占据了文档流空间。通过CSS绝对定位可以让内部表格脱离文档流,实现超出主表格边框显示的效果,具体修改如下:

修改后的代码

Index.razor

@page "/"

<table class="main-table">
    <thead>
        <tr>
            <th/>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody>
        <ExpandRow/>
        <ExpandRow/>
    </tbody>
</table>

<style>
    .main-table {
        border-collapse: collapse;
        margin: 20px;
    }
    .main-table th, .main-table td {
        border: 1px solid black;
        text-align: center;
        white-space: nowrap;
        padding: 8px;
    }

    .expand-container {
        position: relative;
        padding: 0;
    }

    .inner-table-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 10;
        background-color: white;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .inner-table {
        border-collapse: collapse;
    }

    .inner-table th, .inner-table td {
        border: 1px solid #ddd;
        padding: 8px;
        white-space: nowrap;
    }
</style>

ExpandRow.razor

@code {
    private bool IsExpanded { get; set; } = false;
    private void ToggleExpand() { IsExpanded = !IsExpanded; }
}

<tr>
    <td>
        <button @onclick="ToggleExpand">
            @(IsExpanded ? "−" : "+" )
        </button>
    </td>
    <td>Value 1</td>
    <td>Value 2</td>
    <td>Value 3</td>
</tr>

@if (IsExpanded)
{
    <td colspan="10" class="expand-container">
        <div class="inner-table-wrapper">
            <table class="inner-table">
                <thead>
                    <tr>
                        @for (int i = 0; i < 7; ++i)
                        {
                            <th>Inner @i</th>
                        }
                    </tr>
                </thead>
                <tbody>
                    @for (int i = 0; i < 3; ++i)
                    {
                        <tr>
                            @for (int j = 0; j < 7; ++j)
                            {
                                <td>1234.5</td>
                            }
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </td>
}

关键说明

  • 绝对定位脱离文档流:给内部表格的容器.inner-table-wrapper设置position:absolute,使其不再占据主表格单元格的空间,主表格不会被撑开。
  • 相对定位锚点:展开行的单元格.expand-container设置position:relative,让内部表格以该单元格为基准定位。
  • 层级与视觉优化:z-index:10确保内部表格显示在主表格上方,background-color:white避免与下方内容重叠,可选的阴影提升视觉层次感。

内容的提问来源于stack exchange,提问作者mot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:42:37