我有一个设计,当 div 到达窗口内的特定距离时,我试图通过实际添加溢出:隐藏到主体来将其“锁定”到视口(viewport)。我宁愿不必修复它。我的问题:有没有一种方法可以让滚动变得足够精细,从而可以将其触发到特定值?如果我滚动得太快,它就会错过目标。这不是最糟糕的事情,但需要缓慢滚动来参与是有点奇怪的用户体验。
const scrollTop = $(window).scrollTop();
const elementOffset = $("#my-div").offset().top;
const distance = (elementOffset - scrollTop);
if (distance === 75){
this.toggleNoScroll();
}
最佳答案
为了避免“丢失”,您可以存储最后的已知结果并将其与当前状态进行比较。
if (lastDistance < 75 && currentDistance >= 75) {
// Distance is now greater than or equal to 75
} else if (lastDistance >= 75 && currentDistance < 75) {
// Distance is now less than 75
}
// Store the new value
lastDistance = currentDistance;
此外,根据您的用例,position: Sticky
可能是一个可行的替代方案。
关于javascript - 特定像素值的精确滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993751/