gpt4 book ai didi

html - 当我滚动时,如何让我的固定 td 不离开我的 table

转载 作者:行者123 更新时间:2023-11-28 19:30:36 25 4
gpt4 key购买 nike

JavaScript 代码只是我想限制我的 td 在 <h1>big titel</h1> 上移动但在滚动时无法阻止 td 向下移动。我需要让td只在表格区域移动,滚动时不允许td离开表格。

window.onscroll = function() {myFunction()};

var header = document.getElementById("myExemple");
var sticky = header.offsetTop;

function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
#myExemple{
position:fixed;

}
table{
width:50%;
height:250px;

}
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
</style>
</head>
<body>

<table >
<tr valign="top" id="myExemple">
<th>Month</th>
<th>Savings</th>
</tr>
</table>

<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>v<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p><p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>v<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>v<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>

<h1 class="header">
big titel !!!
</h1>
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>v<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p><p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>v<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p><p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p><p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>v<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p><p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>

</body>
</html>

最佳答案

您可能想使用 CSS 的属性 sticky . Mozilla documentation提供了一个适用于您的案例的示例。

在您的 CSS 中,您可以按如下方式更改规则集:

#myExemple {
position: sticky;
top: -1px;
}

Sticky会将元素视为 position:relative而父容器是可见的并且没有滚动。一旦你开始滚动,它就会表现得像 position:absolute ...但相对于父容器。一旦元素离开视口(viewport),它就会回到相对。所以......它是......“粘性”。

这样做,您就不再需要 JavaScript。支持sticky is pretty good , 也。不管 Caniuse 怎么说,我在 Firefox(我的默认浏览器)中对此进行了测试并且没有任何问题。

如果您想解决 Chrome 在应用 position:sticky 时遇到的问题至 <tr> , 你有两个选择

  1. 设置<tr>displaytable-row以外的东西.喜欢inline-block , inline-flex ,或类似的。
  2. 创建一个名为sticky的类并将其应用于 <th> .

In this example我得到一个带有选项 2 的滚动标题。

关于html - 当我滚动时,如何让我的固定 td 不离开我的 table ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55123048/

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