我怎么能简单地冻结我的表的第一行使用纯Javascript,没有插件

How can I simply freeze the first row of my table using pure Javascript, no plugins?

本文关键字:一行 Javascript 插件 冻结 简单 怎么能 我的      更新时间:2023-09-26

我只需要这个表在最新版本的Google Chrome中工作(因此无需担心跨浏览器解决方案,如旧版本的IE等)

我正在寻找一个解决方案来冻结第一行,没有任何成功。如果我在这个CSS position: fixed relative;中排除单词relative,那么标题行堆叠在彼此的顶部。不知道如何让标题停留在屏幕的顶部,当我滚动

表的代码

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $( "#status_report .measure[data-bg='1']").css('background', 'red');
    $( "#status_report .measure[data-bg='2']").css('background', 'grey');
    $( "#status_report .measure[data-bg='3']").css('background', 'yellow');
    $( "#status_report .measure[data-bg='4']").css('background', 'green');
});
</script>
<style type="text/css">
th{
    position: fixed relative;
    background:#111;
    color:#fff;
    padding: 2px;
}
td
{
    background:#ddd;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 2px;
}
</style>
</head>
<body>
<table id="status_report">
<tr>
    <th>field1</th>
    <th>field2</th>
    <th>field3</th>
</tr>
<tr>
<?php foreach( $data as $row ) : ?>
<tr>
    <td><?php echo $row['field1']; ?></td>
    <td class = "measure" data-bg="<?php echo $row['field2']; ?>"><?php echo $row['field2']; ?></td>    
    <td class = "measure" data-bg="<?php echo $row['field3']; ?>"><?php echo $row['field3']; ?></td>        
</tr>
<? endforeach;
$dbh = null; ?>
</table>
</body>
</html>

position: fixed relative为无效CSS。当你将某物设置为fixed时,它的位置"重置",就像这样,对象不会停留在"它应该在的地方",而是相对于文档,所以你需要使用top, left等来设置它的位置。

这就是它们叠起来的原因。

您可以为此定义一个JScrollpane。

但是如果用户不在JScrollPane的焦点上,它将不起作用。因此,如果用户在JScrollPane之外,您可以捕获onscroll事件并重置位置。

下面是一个例子:

http://christian-illies.info/2011/11/javascript-scrollbalken-mit-jscrollpane/