javascript - 我怎样才能使用纯 Javascript 而不使用插件来简单地卡住表格的第一行?

标签 javascript html css html-table tableheader

我只需要这个表在最新版本的谷歌浏览器中工作(所以不用担心跨浏览器的解决方案,比如旧版本的 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

定位

这就是它们堆叠的原因。

Read more about positioning .

关于javascript - 我怎样才能使用纯 Javascript 而不使用插件来简单地卡住表格的第一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15830780/

相关文章:

html - 使用显示时 Google map 被裁剪 :Inherit;

javascript - 如何返回此 AJAX 调用的结果?

javascript - Bootstrap 弹出窗口更新内容

html - CSS - 移动设备

javascript - 如何仅在分配时应用 Webkit-input-placeholder

html - 悬停时的动态滚动条对内容造成跳跃效果

asp.net - HtmlGenericControl 对象引用未设置为对象的实例

javascript - 了解 JavaScript 中的 HTML 字符串转义

c# - 单击按钮时显示 Div

html - 在表格中间对齐图标