利用jQuery制作简易的table上下无缝轮播

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
 <style>
 .box {
 /* 最外层可显示的高度 */
 height: 200px;
 overflow: hidden;
 }
 .table {
 width: 600px
 }
 .thead,
 .tbody {
 position: relative;
 }
 .thead {
 z-index: 1;
 background: darkgray;
 }
 .tbody {
 z-index: 0;
 }
 </style>
</head>
<body>
 <div class="box">
 <table class="table" border=1 cellspacing=0>
 <thead class="thead">
 <tr>
 <th>序号</th>
 <th>名字</th>
 <th>年龄</th>
 <th>性别</th>
 <th>测试1</th>
 </tr>
 </thead>
 <tbody class="tbody">
 </tbody>
 </table>
 </div>
 <script>
 // 加载数据
 for (let i = 0; i < 20; i++) {
 var row = [
 '<tr>',
 '<td title="' + i + 1 + '">' + i + 1 + '</td>',
 '<td>' + '名字' + i + '</td>',
 '<td>' + '年龄' + i + '</td>',
 '<td>' + '性别' + i + '</td>',
 '<td>' + '测试1--' + i + '</td>',
 '</tr>'
 ].join('')
 console.log(row)
 $('.box tbody').append(row)
 }
 startRoll(50) //50为时间
 function startRoll(time) {
 let timer = null
 //默认初始值为自己本身的top
 let top = $(".tbody").css('top')
 let offsetTop = top.substring(0, top.indexOf('px'))
 startFun(time)
 function startFun(time) {
 timer = setInterval(() => {
 //比较数据的长度是否超过div的高度,没超过不开始轮播
 if (!heightComparison()) {
 clearTimeout(timer)
 return false
 }
 offsetTop -= 1
 let body_tbody = $("tbody") //定义 tbody为body_tbody
 let scrollHeight = body_tbody.find("tr").outerHeight(true); //获取 tr的高度
 
 let tbodyTopPX = body_tbody.css('top'); // 获取tbody的top值
 let tbodyTop = tbodyTopPX.substring(0, tbodyTopPX.indexOf('px'))
 
 body_tbody.css({ 'top': offsetTop + 'px' }) //改变tbody的top 令tbody向上移动
 
 if (tbodyTop != 0 && parseInt(tbodyTop) % Math.ceil(scrollHeight) === 0) { // tbodyTop的top值是 tr高度的倍数时 将第一个tr移动到最后并让tbodyTop的top值减去tr的高度
 body_tbody.find("tr:first").appendTo(body_tbody);
 offsetTop += scrollHeight
 body_tbody.css({ 'top': offsetTop + 'px' })
 }
 }, time)
 }
 $(".box").mouseover(function () {
 // 鼠标移入 关闭轮播
 clearTimeout(timer)
 });
 $(".box").mouseout(function () {
 // 鼠标移出 重新开启轮播
 startFun(time)
 });
 }
 function heightComparison() {
 let divHeight = $(".box").height(); //最外层div的高度 用来比较数据的长度是否超过div的高度,没超过不开始轮播
 let tbodyHeight = $(".tbody").height();
 let tHeadHeight = $(".thead").height();
 return tbodyHeight > divHeight - tHeadHeight
 }
 </script>
</body>
</html>

 

作者:Z-HarOld原文地址:https://www.cnblogs.com/Z-HarOld/p/17483052.html

%s 个评论

要回复文章请先登录注册