我尝试根据W3Schools上的解决方案实现一个粘性表头:
https://www.w3schools.com/howto/howto_js_sticky_header.asp
然而,我的表头仍然不能随着滚动而固定。控制台日志显示
以下是我的代码概要:
sticky
、window.pageYOffset
和header.offsetHeight
的值与预期相符。我是否漏掉了什么?以下是我的代码概要:
<html lang="en">
<head>
<style type="text/css">
/*...*/
#myTable {
float:left;
width:75%;
background-color:#fff;
padding:6px;
margin-left:175px;
}
#myTable th {
cursor:pointer;
position: sticky;
top: 0;
}
#myTable th:hover {
background-color:#66991c;
color:white;
}
#myTable tr:nth-child(even) {
background-color:#eee;
}
#myTable tr:nth-child(odd) {
background-color:#fff;
}
#table-link {
display:block;
text-decoration:none;
background-color:black;
color:white;
border-radius:5px;
}
#table-link a {
display:block;
text-decoration:none;
background-color:black;
color:white;
border-radius:5px;
}
#table-link a:hover {
display:block;
text-decoration:none;
background-color:#66991c;
color:white;
border-radius:5px;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
/*...*/
</style>
</head>
<body>
...
<table id="myTable">
<div id="myHeader">
<caption>...</caption>
<thead>...</thead>
</div>
<tbody>...</tbody>
</table>
...
<script>
window.onscroll = function() {myFunction()};
var header = document.getElementById("myHeader");
var sticky = header.offsetTop;
function myFunction() {
if (window.pageYOffset > sticky) {
header.style.paddingTop = header.offsetHeight + 'px';
header.classList.add("sticky");
} else {
header.style.paddingTop = 0;
header.classList.remove("sticky");
}
}
</script>
</body>
</html>
.sticky
。 - AndrewL64<table>
不能直接包含一个div。对我来说,Firefox会将<div>
移动到表格外面,但是会将<caption>
留在里面,这意味着你看不到代码是否按照预期工作。position: sticky
。