<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="wi ...
<!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>