我正在这个项目上工作,在这里我既需要滚动侦听器又需要滚动捕捉,因此我可以在部分更改之间做出一些很酷的过渡效果。我可以让这两个单独工作,但不能一起工作。滚动捕捉要求容器元素(main
元素)具有高度,但是当我给它一个height: 100%
时,JS滚动侦听器停止工作。我尝试了所有已知的知识,尝试更改其他容器的高度/溢出属性,并尝试定位到body
或window
以外的其他元素。最好的解决方法是什么?
此处的代码段已调整为可与侦听器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>
答案 0 :(得分:1)
在另一个主题中,@ lawrence-witt说我必须将事件侦听器添加到Imagick::annotateImage
,而不是整个main
。使用window
时,滚动捕捉和滚动事件侦听器都可以正常工作。
main.addEventListener('scroll', scrollEvent);
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";
}
}
main.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;
height: 100%;
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;
}