【发布时间】:2020-05-12 20:36:32
【问题描述】:
我正在做这个项目,我需要滚动监听器和滚动捕捉,这样我就可以在部分更改之间制作一些很酷的过渡效果。我可以让这两个单独工作,但不能一起工作。滚动捕捉需要容器元素(main 元素)有一个高度,但是当我给它一个 height: 100% 时,JS 滚动监听器停止工作。我尝试了我所知道的一切,尝试更改其他容器的高度/溢出属性,并尝试针对body 或window 之外的其他元素。最好的解决方法是什么?
此处的 sn-p 已调整为与侦听器 ATM 一起使用。如果您继续将height: 100% 添加到main,您将看到滚动捕捉开始工作但事件侦听器中断。
const scrollEvent = () => {
const main = document.querySelector('#main');
const section1 = document.querySelector('#sect1');
const section2 = document.querySelector('#sect2');
if (main.scrollTop > 50) {
section1.style.backgroundColor = "red";
} else {
section1.style.backgroundColor = "pink";
}
if (main.scrollTop > window.innerHeight / 2) {
section2.style.backgroundColor = "blue";
} else {
section2.style.backgroundColor = "purple";
}
}
window.addEventListener('scroll', scrollEvent);
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
width: 100%;
}
body {
scroll-behavior: smooth;
}
main {
display: flex;
flex-direction: column;
width: 100vw;
overflow: auto;
scroll-snap-type: y mandatory;
}
section {
flex-basis: 100vh;
flex-grow: 1;
flex-shrink: 0;
width: 90vw;
border: 1px solid red;
margin: 0 auto;
}
main section {
scroll-snap-align: start;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<main id="main" dir="ltr">
<section id="sect1">
<h1>content1</h1>
</section>
<section id="sect2">
<h1>content2</h1>
</section>
</main>
</body>
</html>
【问题讨论】:
-
具体问题是
overflow: auto;on main。摆脱它可以让它工作。 -
我不知道怎么做。使用
overflow: auto滚动快照不起作用
标签: javascript css