如何正确设置粘性表头的样式?

Jar*_* K. 7 html css css-tables angular

我的数据表中的样式粘贴标题有点问题.我编写了简单的Angular组件和特定的指令:

sticky.directive.ts

@Directive({
    selector: '[sticky]'
})
export class StickyDirective {

    constructor(private _element: ElementRef, private _window: WindowRef) {
        console.log('debug')
    }

    @HostListener('window:scroll', ['$event'])
    handleScrollEvent(e) {
        if (this._window.nativeWindow.pageYOffset > 100) {
            this._element.nativeElement.classList.add('stick');
        } else {
            this._element.nativeElement.classList.remove('stick');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果用户在标题下滚动,则该指令的目的是添加类标记.因此,表头应该对用户可见,即使他滚动长表也是如此.类看起来像那样:

.stick {
    position: fixed;
    top: 55px;
} 
Run Code Online (Sandbox Code Playgroud)

我的some.component.html(和thead元素上的use指令)的一部分看起来像:

<table class=" table table-bordered ">
 <thead sticky>
   <tr>
    <th width="40%">Name
    </th>
    <th width="10%">Priority
    </th>
    <th width="25%">Date created
    </th>
    <th width="25%">Date modified
    </th>   </tr>   </thead>   <tbody>   <tr *ngFor="let r of entitiesFiltered">
    <td>
      <div class="table-cell-flex">
        <div class="cell-content">
          {{r.name}}
        </div>
      </div>
    </td>
    <td>
      <div class="table-cell-flex">
        <div class="cell-content">
          {{r.priority}}
        </div>
      </div>
    </td>
...
Run Code Online (Sandbox Code Playgroud)

我的代码符合基本功能.这意味着在滚动页面期间标题保留在同一位置,但标题宽度和列宽度会更改.它看起来像:在此输入图像描述


题:

任何人都可以告诉我如何设置我的表格,固定标题不会改变表格/形状表?可能吗?

小智 0

您可以使用 javaScript 获取任何列的宽度,然后将 px 设置为固定或绝对位置的标题,或者使用 html 和代码:

<div class="table-wrapper content">
  <!-- overall wrapper -->
  <table>
    <!-- header -->
    <thead>
      <tr>
        <th>Header 1</th>
        <th>Header 2</th>
        <th>Header 3</th>
      </tr>
    </thead>
  </table>
</div>
<div class="table-body-wrapper" style="position: relative; overflow: visible;">
  <!-- the element with the custom scrollbar -->
  <table>
    <!-- body -->
    <tbody>
      <!-- auto-generated data (see js function below) -->
      <tr>
        <td>Row 1, Column 1</td>
        <td>Row 1, Column 2</td>
        <td>Row 1, Column 3</td>
      </tr>
      <tr>
        <td>Row 2, Column 1</td>
        <td>Row 2, Column 2</td>
        <td>Row 2, Column 3</td>
      </tr>
      <tr>
        <td>Row 3, Column 1</td>
        <td>Row 3, Column 2</td>
        <td>Row 3, Column 3</td>
      </tr>
      <tr>
        <td>Row 4, Column 1</td>
        <td>Row 4, Column 2</td>
        <td>Row 4, Column 3</td>
      </tr>
      <tr>
        <td>Row 5, Column 1</td>
        <td>Row 5, Column 2</td>
        <td>Row 5, Column 3</td>
      </tr>
    </tbody>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)