这是jsfiddle:https ://jsfiddle.net/g421kjcx/
这是我对您的小提琴的回应:https ://jsfiddle.net/5nfb2qdy/4/
我回答了你在这篇文章中提出的一系列问题:
如您所见,这是有效的,但仅适用于顶部单元格。...我如何“定位”第一列中的所有 td。
1)观察者的目标是单个元素(在这种情况下)。这意味着您不能依赖它来设置多个元素的样式。相反,这样做:
([e]) => {
let all_td = document.querySelectorAll('.wdtscroll td:first-child')
all_td.forEach(entry =>
entry.classList.toggle('isSticky', e.intersectionRatio < 1)
)
}
当我在我的网站上使用此代码时,它不起作用,并且我收到一条警告:“TypeError:IntersectionObserver.observe 的参数 1 不是对象。”
2) 这很可能是因为 JavaScript 是在页面上引用的元素甚至存在之前运行的。如果此代码块在<head></head>
页面的一部分中,则只需稍作修改即可使其工作:
window.onload = function(){
observer.observe(stickyElm)
}
通过将观察者激活包装在 中onload
,它不会在页面完成渲染之前运行。另一种选择是将所有这些 JavaScript 移动到页面末尾,就在您的</body></html>
额外的问题:当第二列或 .wdtscroll td:nth-child(2) 卡住时,我将如何设置它的样式,即使它永远不会滚动到视口之外。
3)也许像这样?
([e]) => {
let all_td = document.querySelectorAll('.wdtscroll td:nth-child(1)')
let all_2nd_td = document.querySelectorAll('.wdtscroll td:nth-child(2)')
all_td.forEach(entry =>
entry.classList.toggle('isSticky', e.intersectionRatio < 1)
)
all_2nd_td.forEach(entry =>
entry.classList.toggle('isSticky', e.intersectionRatio < 1)
)
}
还要将其添加到 CSS 的末尾:
.wdtscroll tr td:nth-child(2).isSticky {
background-color: pink;
}
4) 没有回答您的任何问题,但我注意到您的 CSS 通常存在一些问题。以下是我更改的内容:
CSS
/* added td to the selectors of the next 2 rules */
.wdtscroll tr:nth-child(even) td { background-color: #f2f2f2; }
.wdtscroll tr:hover td { background-color: #ddd; }
/* added tr to the selector list to override the background color set above */
.wdtscroll tr td.isSticky{
background-color: salmon;
}
5) 最后,对用于对元素进行类分配的方法进行批评。您可能有充分的理由为td
每个tr
. 这也可以更简单地通过将类属性分配给表格本身来实现,该表格本身具有应用样式的规则td:nth-child(1)
并且td:nth-child(2)
仅具有 2 个 CSS 规则。这将消除在 JavaScript 中遍历表格的每一行的需要,并利用 CSS 的特性来设置大容量元素的样式。
CSS:
.wdtscroll.isSticky tr td:nth-child(1) {
background-color: salmon;
}
.wdtscroll.isSticky tr td:nth-child(2) {
background-color: pink;
}
JavaScript:
// get the sticky element
const stickyElm = document.querySelector('.wdtscroll td')
const tableElm = document.querySelector('.wdtscroll')
const observer = new IntersectionObserver(
([e]) => {
tableElm.classList.toggle('isSticky', e.intersectionRatio < 1)
},
{threshold: [1]}
);
window.onload = function(){
observer.observe(stickyElm)
}
一个漂亮、整洁、整洁的解决方案怎么样?:) 最后的小提琴:https ://jsfiddle.net/5nfb2qdy/5/