看看下面的代码(另外,你需要jquery.js、jquery.viewport.js和jquery.scrollTo.js)。
我希望从这个脚本中得到的行为是,每当我滚动页面时,应该将红色行(<tr>
带有 class 的元素)插入到该表最顶部可见行(元素)的alwaysVisible
下方。<tr>
然后,页面应该滚动,以便这些红色行中的第一行“完全”出现在视口的顶部。实际发生的是makeVisibleWhatMust();
重复调用,直到我到达页面末尾。我以为$(window).unbind('scroll');
会makeVisibleWhatMust();
不再被调用,但显然这不起作用。
任何想法为什么?
这是我写的 JavaScript:
function makeVisibleWhatMust()
{
$('#testContainer').text( $('#testContainer').text() + 'called\n');
$('table.scrollTable').each
(
function()
{
var table = this;
$($('tr.alwaysVisible', table).get().reverse()).each
(
function()
{
$(this).insertAfter( $('tr:in-viewport:not(.alwaysVisible)', table)[0] );
}
);
$(window).unbind('scroll');
$(window).scrollTo( $('tr.alwaysVisible')[0] );
$(window).bind('scroll', makeVisibleWhatMust);
}
);
}
$(document).ready
(
function()
{
$(window).bind('scroll', makeVisibleWhatMust);
}
);
这是一个用于测试它的 HTML 页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Scroll Tables Test Page</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="jquery.viewport.js"></script>
<script type="text/javascript" src="jquery.scrollTo.js"></script>
<script type="text/javascript" src="scrollTable.js"></script>
<style type="text/css">
table th, table td
{
border: 1px solid #000;
padding: .3em;
}
.alwaysVisible
{
background: #F66;
}
</style>
</head>
<body>
<table class="scrollTable">
<thead>
<tr class="alwaysVisible">
<th>Row name</th>
<th>Content</th>
</tr>
<tr class="alwaysVisible">
<th>Row 2</th>
<th>Row 2</th>
</tr>
</thead>
<tbody>
<script type="text/javascript">
for(var i = 0; i < 50; ++i)
{
document.writeln("<tr><td>Row " + i + "</td><td>Content</td></tr>");
}
</script>
</tbody>
<tfoot>
<tr>
<td>Footer</td>
<td>Footer 2</td>
</tr>
</tfoot>
</table>
<div id="testContainer">TEST CONTAINER</div>
</body>
</html>