CSS表格固定表头示例

  css+JavaScript实现表格的表头固定效果,页面滚动,表头处于页面最顶端。

CSS表格固定表头示例

  CSS表格固定表头示例代码如下

<!doctype html>
<html >
<head>
<title>CSS表格固定表头</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<style type="text/css">
* html,* html body /* 修正IE7振动/闪动bug */{background-image:url(about:blank);background-attachment:fixed;}
body {margin: 0;padding: 0;}
td {width: 200px;line-height: 30px;}
table {width: 2000px; }
#th {background-color: #888888;position: fixed;/*IE8+和标准浏览器fixed定位*/ width: 2000px;height: 30px;top: 0;left: 0;}
#wrap {position: relative;padding-top: 30px;}
</style>
<!--小于IE8增加css expression结合上面的修正css才有用,用js的onscroll事件来设置top属性还是会闪动。-->
<!--[if lt IE 8]>
<script>var ie7min=true</script>
<style>#th{position:absolute;top:expression(eval(document.documentElement.scrollTop));}</style>
<![endif]-->
<script type="text/javascript">
    if (!window.ie7min) {//IE8+和标准浏览器fixed定位,当有水平滚动条,水平滚动时需要设置fixed定位对象的left属性,要不会滚动导致表头和内容无法对齐
        var obj_th, sl, osl ;
        window.onload = function () {
            obj_th = document.getElementById("th");
            osl = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
            window.onscroll = function () {
                sl = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
                if (sl != osl) {
                    obj_th.style.left = -sl + 'px'
                    osl = sl;
                }
            };
        };
    }
</script>
</head>
<body style="height:2000px">
<div id="wrap">
<table cellpadding="0" cellspacing="0">
<tr id="th">
<script>
    var col = 10;
    for (var i = 0; i < col; i++) document.write('<td>表头' + i + '</td>')
</script>
</tr>
<script>
    for (var j = 0; j < 30; j++) {
        document.write('<tr>');
        for (var i = 0; i < col; i++) document.write('<td>内容' + j + '-' + i + '</td>');
        document.write('</tr>');
    }
</script></table></div></body>
</html>

 


原创文章,转载请注明出处:CSS表格固定表头示例

评论(0)Web开发网
阅读(883)喜欢(0)不喜欢(1)HTML/CSS兼容/XML