在除 Firefox 之外的传统浏览器上使用滚动事件对 CSS 进行动画处理的奇怪行为



我正在使用css网格处理一个简单的图库,并且当用户向下滚动时,我正在尝试对项目之间的间隙进行动画处理。但我不知道为什么我在铬和边缘上会出现这种奇怪的行为,当我尝试滚动时,每个项目都会按高度缩小。它在 Firefox 中运行良好,引擎盖下的所有内容似乎都运行良好,我没有收到任何错误,我尝试在我的 css 上使用自动前缀器,但它没有任何帮助。

<div class="container" id="container">
...images goes here (sm,md,lg classes)
</div>
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-auto-rows: minmax(10%, 20%);
grid-auto-flow: dense;
transition: all 1s;
transition-delay: 0.1s;
gap: 1rem;
padding: 0 1rem;
}
img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 2px;
}
.sm {
grid-row: span 1;
}
.md {
grid-row: span 5;
}
.lg {
grid-row: span 6;
}
.scroll-animation {
gap: 0.1rem;
padding: 0 0.1rem;
}
let lastScrolled = 0; // Number of pixels the user has scrolled in the last event
// Basically we want to add "scroll-animation" to the container when the user scrolled down
// This state controlls event calls
let fired = false;
window.addEventListener('scroll', (e) => {
const scrollable = document.documentElement.scrollHeight - window.innerHeight; // Numbers of pixels the user can scroll
const scrolled = window.scrollY; // Number of pixels the user has scrolled
if (fired === false) {
fired = true;
// If the user scrolls down the scrolled value increases and vice versa
// So basically
if (scrolled < lastScrolled) {
// Then the user scrolled up
console.log('GET OUT! YOU SCROLLED UP!');
// But you should update the lastScrolled value nonetheless
lastScrolled = scrolled;
setTimeout(() => {
// not the best kind of solution
fired = false;
}, 500);
return; // And then get out!
}
// Before we continue
// It gets weird when it reaches the bottom of page so i had to add this fix
// Checks if the user scrolled all the way to the bottom of page and returns
if (Math.ceil(scrollable) === scrolled) {
console.log('STOP!');
fired = false;
return;
}
// And finally you need a setTimeOut function for this to work
// Because you need to add and remove the "scroll-animation" class between some kind of time interval
// Add class as soon as the scroll event starts
container.classList.add('scroll-animation');
// And remove it after the time interval
setTimeout(() => {
container.classList.remove('scroll-animation');
fired = false;
console.log('Scrolling has stopped.');
}, 1050);
}
lastScrolled = scrolled; // The value gets updated in any case
});

代码笔

出于某种原因,如果您不指定heightdiv.container会发疯

grid-gap: 0.1rem属性似乎导致了问题。

html, body {
height: 100%;
}
.container {
height: 100%;
...rest...
}

grid-column: span minmax(2, 3);也不起作用。

最新更新