【问题标题】:Horizontally and vertically scrollable content with fixed header具有固定标题的水平和垂直可滚动内容
【发布时间】:2013-09-02 00:37:18
【问题描述】:

我有一个动态宽度的内容 div(它会根据窗口宽度自行调整)。在这个 div 中,我有两个比我的包装 div 的视口更宽的表。因此包装器应该是水平滚动的。 div 也有一个固定的高度,这意味着一切都应该是垂直滚动的!只是标题应该保持在顶部,但也应该与内容表一起水平滚动。

<div class="wrapper">
    <table width="2000" class="fixed"><tr></tr></table>
    <table width="2000"><tr></tr></table>
</div>

这里有一个小提琴来演示我的问题:jsFiddle

【问题讨论】:

  • 你的意思是当用户向下滚动时,'header' 表应该始终保持可见?
  • 是的,我就是这个意思!它应该可以垂直和水平滚动,但标题应该保持在顶部。
  • 简单地将&lt;div class="mega"&gt;(第1行)向下移动到&lt;table width="2000"&gt;(第5行)上方
  • 这样标题就不能和内容表一起水平滚动了。

标签: javascript html css


【解决方案1】:

演示: http://jsfiddle.net/techsin/pDhmy/4/

标题宽度变化: http://jsfiddle.net/techsin/pDhmy/8/

执行此操作的代码

$('.mega').on('scroll',function(){$('.header').css('top',$(this).scrollTop());});

和....

.header{position:absolute; background-color:rgb(202, 202, 202);}

.header+* {margin-top:30px;}

【讨论】:

  • 不错的解决方案,但不幸的是,当第二个“表格”中的内容更宽时(例如jsfiddle.net/gvee/pDhmy/5),这会中断......我想我们可以为列设置固定宽度?
  • 那是因为这两个是不同的表。这就是OP结构。当它是正常的并且滚动所有这将是这种情况时意味着事件。 jsfiddle.net/techsin/pDhmy/6
  • 将此添加到 CSS 可以缓解问题,但并不理想 .mega td { width: 25%; }
  • 我之所以选择这种结构,是因为我认为使用一张桌子并操纵头部是行不通的。另一个问题是我有多个具有不同表格和单元格编号的视图。但如果这是最好的实现,我将不得不扩展我的后端并为每个视图的每个单元格分配一个特定的宽度。
  • 我没有必要让 jquery 将标题调整为底部单元格的宽度。 jsfiddle.net/techsin/pDhmy/7
【解决方案2】:

粘性表格标题

演示: http://jsfiddle.net/gvee/kJ9xp/

HTML

<table>
    <thead>
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th>D</th>
    </thead>
    <tr class="sticky-header">
        <th>A</th>
        <th>B</th>
        <th>C</th>
        <th>D</th>
    </tr>
    <tr>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
    </tr>
    <tr>
        <td>2</td>
        <td>2</td>
        <td>2</td>
        <td>2</td>
    </tr>

    ... etc ...

</table>

CSS

* {
    margin: 0;
    border: 0;
    padding:0;
}

table {
    border-collapse: collapse;
    margin: 10px;
}

th, td {
    width: 50px;
    height: 50px;
    background-color: #eee;
    text-align: center;
    border: 1px solid #ddd;
}

.sticky-header {
    display: none;
    position: fixed;
    top: 0px;
}
.sticky-header th {
    background-color: red;
}

jQuery

​​>
var thead = $('thead');
var th = $('.sticky-header');
var t = $('table');

$(document).scroll(function() {
    if ($(this).scrollTop() >= thead.offset().top && $(this).scrollTop() < t.offset().top + t.height() - th.height())
    {
        th.show();
    } else {
        th.hide();
    }
});

【讨论】:

  • 效果不错。但是有一个问题。每次你需要 div 来点击屏幕的最顶部。假设您希望滚动小部件滚动而不滚动整个页面。如果不每次都更改代码,这将无法工作。看一看:jsfiddle.net/techsin/kJ9xp/2
  • @MuhammadUmer 我刚刚注意到,当再次使用代码时...感谢 cmets - 我将把它带回绘图板并尝试提出更灵活和正确的解决方案
猜你喜欢
  • 1970-01-01
  • 2016-08-29
  • 2019-08-15
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 2016-10-11
  • 2020-04-08
相关资源
最近更新 更多