原码笔记

原码笔记

利用css3 translate完美实现表头固定效果

小诸哥 0

前言

前段时间在工作中正好需要这个功能,但是找了很多都不能完美的实现,所以在此就自己做了一个固定表头的方法,主要用到了css3中的translate和一小段js代码,下面来一起看看吧。

效果如下:

感觉是不是很和谐,而且代码也少,不足的是IE9以下不支持translate属性,但现在也没多少要考滤IE9以下的兼容了吧,做前端老兼顾低版本的浏览器难免会让自己束手束脚。。。。

下面来看下代码吧

HTML

  1. <div class="box">
  2.      <table>
  3.          <thead>
  4.              <tr>
  5.                  <th>1</th>
  6.                  <th>2</th>
  7.                  <th>3</th>
  8.                  <th>4</th>
  9.                  <th>5</th>
  10.                  <th>6</th>
  11.                  <th>7</th>
  12.                  <th>8</th>
  13.                  <th>9</th>
  14.                  <th>10</th>
  15.                  <th>11</th>
  16.                  <th>12</th>
  17.                  <th>13</th>
  18.                  <th>14</th>
  19.                  <th>15</th>
  20.              </tr>
  21.          </thead>
  22.          <tbody>
  23.              <script>
  24.              var tr = '';
  25.              for(var i=0; i<15; i++) {
  26.                  tr += '<tr>\
  27.                      <td>'+i+'</td>\
  28.                      <td>'+i+'</td>\
  29.                      <td>'+i+'</td>\
  30.      <td>'+i+'</td>\
  31.                      <td>'+i+'</td>\
  32.                      <td>'+i+'</td>\
  33.                      <td>'+i+'</td>\
  34.                      <td>'+i+'</td>\
  35.                      <td>'+i+'</td>\
  36.                      <td>'+i+'</td>\
  37.                      <td>'+i+'</td>\
  38.                      <td>'+i+'</td>\
  39.                      <td>'+i+'</td>\
  40.                      <td>'+i+'</td>\
  41.                      <td>'+i+'</td>\
  42.                      </tr>';
  43.              }
  44.              document.write(tr);
  45.              </script>
  46.          </tbody>
  47.      </table>
  48. </div>

CSS样式

  1. <style>
  2. *{ margin: 0; padding: 0; list-style: none;}
  3. .box {
  4.      width: 300px;
  5.      height: 300px;
  6.      margin: 50px auto 0;
  7.      overflow: auto;
  8. }
  9. .box table{
  10.      width: 100%;
  11.      border-collapse: collapse;
  12.      border-right: 1px solid #ccc;
  13.      border-top: 1px solid #ccc;
  14.      text-align: center;
  15. }
  16. .box table thead {
  17.      background-color: #ccc;
  18. }
  19. .box table th,
  20. .box table td {
  21.      padding: 8px 10px;
  22.      border-left: 1px solid #ccc;
  23.      border-bottom: 1px solid #ccc;
  24.      white-space: nowrap;
  25. }
  26. </style>

JS脚本

  1. <script>
  2. window.onload = function() {
  3.      var $ = document.querySelector.bind(document);
  4.      var boxEle = $('.box');
  5.      boxEle.addEventListener('scroll', function(e) {
  6.          this.querySelector('thead').style.transform = 'translate(0, '+this.scrollTop+'px)';
  7.      });
  8. }
  9. </script>

总结

好了,以上就是这篇文章的全部内容了,代码是不是真的很少呢,还在等什么?快点感受一下吧。希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

标签: 实现 效果