How to: Fixed Table Header with ONE table (no jQuery)

天大地大妈咪最大 提交于 2019-11-27 13:22:20

Ok i got it:

You need to wrap the table in two DIVs:

<div class="outerDIV">
  <div class="innerDIV">
    <table></table>
  </div>
</div>

The CSS for the DIVs is this:

.outerDIV {
  position: relative;
  padding-top: 20px;   //height of your thead
}
.innerDIV {
  overflow-y: auto;
  height: 200px;       //the actual scrolling container
}

The reason is, that you basically make the inner DIV scrollable, and pull the THEAD out of it by sticking it to the outer DIV.

Now stick the thead to the outerDIV by giving it

table thead {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

The tbody needs to have display: block as well.

Now you'll notice that the scrolling works, but the widths are completely messep up. That's were Javascript comes in. You can choose on your own how you want to assign it. I for myself gave the TH's in the table fixed widths and built a simple script which takes the width and assigns them to the first TD-row in the tbody.

Something like this should work:

function scrollingTableSetThWidth(tableId)
{
    var table = document.getElementById(tableId);

    ths = table.getElementsByTagName('th');
    tds = table.getElementsByTagName('td');

    if(ths.length > 0) {
        for(i=0; i < ths.length; i++) {
            tds[i].style.width = getCurrentComputedStyle(ths[i], 'width');
        }
    }
}

function getCurrentComputedStyle(element, attribute)
{
    var attributeValue;
    if (window.getComputedStyle) 
    { // class A browsers
        var styledeclaration = document.defaultView.getComputedStyle(element, null);
        attributeValue = styledeclaration.getPropertyValue(attribute);
    } else if (element.currentStyle) { // IE
        attributeValue = element.currentStyle[vclToCamelCases(attribute)];
    }
    return attributeValue;
}

With jQuery of course this would be a lot easier but for now i was not allowed to use a third party library for this project.

Maybe we should change a method to archieve this goal.Such as:

<div><ul><li>1</li><li>2</li></ul></div> //make it fixed
<table>
    <thead>
        <tr><th>1</th><th>2</th></tr>
    </thead>
    <tfoot></tfoot>
    <tbody></tbody>
</table>

Of course, this is not good to sematic.But it is the simplest way without js or jq. Don't you think so?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!