利用javascript实现表格内容向上自动滚动轮播

2024年08月22日 建站教程

利用html+css+javascript实现表格内容向上自动滚动轮播,下面web建站小编给大家介绍一下具体实现代码!

html代码:

<div id="box">
  <table id="table">
    <thead class="table-thead">
      <tr>
        <th>姓名</th>
        <th>城市</th>
        <th>数量</th>
      </tr>
    </thead>
    <tbody class="table-tbody">
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
      <tr>
        <td>王小米</td>
        <td>哈尔滨</td>
        <td>100</td>
      </tr>
    </tbody>
  </table>
</div>

css代码:

* {
  margin:0px;
  padding:0px;
}
.table-tbody td {
  width:180px;
  text-align:center;
}
table tr {
  height:40px;
}
#box {
  height:200px;
  width:720px;
  overflow:hidden;
}
.table-thead {
  position:sticky;
  top:0;
  background-color:#eee;
}

javascript代码:

window.onload = function() {
  var box = document.getElementById("box");
  var table = document.getElementById("table");
  box.scrollTop = 0;
  var timer = null;
  timer = setInterval(function() {
    box.scrollTop++;
    if (box.scrollTop > box.offsetHeight) {
      box.scrollTop = 0;
    }
  }, 30);
  box.onmouseover = function() {
    clearInterval(timer)
  }
  box.onmouseout = function() {
    timer = setInterval(function() {
      box.scrollTop++;
      if (box.scrollTop > box.offsetHeight) {
        box.scrollTop = 0;
      }
    }, 30)
  };
}

本文链接:http://so.lmcjl.com/news/11436/

展开阅读全文
相关内容