gpt4 book ai didi

javascript - 确定 html 表中的第一行

转载 作者:可可西里 更新时间:2023-11-01 13:40:18 27 4
gpt4 key购买 nike

我有一个带滚动条的 html 表格(即设置了溢出)。当我滚动表格时,我想获得当前顶行的位置(即根据表格的用户 View )。

我该怎么做?

你们谁能帮我举个例子吗?

最佳答案

如果您要使用 vanilla JavaScript,这里可能会帮助您入门。它绝对不完美,但可能会激发一些想法... JSFiddle Example

[更新] 来自上面链接的代码

JavaScript

document.getElementById('btn').onclick = function() {
var tbl = document.getElementById('tbl');
var scrollAmt = document.getElementById('asdf').scrollTop;
var totalRowHeight = 0,
viewTolerance = 1/3, //if only 1/3 of row is showing highlight next row
rowHeight;

for( var i = 0; i < tbl.rows.length; i++ ) {
totalRowHeight += rowHeight = tbl.rows[i].offsetHeight;
if( totalRowHeight > scrollAmt ) {
//if row doesn't meet viewTolerance requirement highlight next row
var rowIndex = (totalRowHeight - scrollAmt < rowHeight*viewTolerance) ? i + 1: i;
tbl.rows[rowIndex].style.backgroundColor = '#ff00ff';
break;
}
}
}

HTML

<div id="asdf">
<table id="tbl">
<tbody>
<tr><td>asdf</td><td>asdf1</td></tr>
<tr><td>asdf</td><td>asdf2</td></tr>
<tr><td>asdf</td><td>asdf3</td></tr>
<tr><td>asdf</td><td>asdf4</td></tr>
<tr><td>asdf</td><td>asdf5</td></tr>
<tr><td>asdf</td><td>asdf6</td></tr>
<tr><td>asdf</td><td>asdf7</td></tr>
<tr><td>asdf</td><td>asdf8</td></tr>
</tbody>
</table>
</div>
<input type="button" value="getTop()" id="btn" />

CSS

#asdf{
height:100px;
overflow:scroll;
}

关于javascript - 确定 html 表中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384378/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com