gpt4 book ai didi

javascript - 如何让 CSS 滚动捕捉与 JS 滚动事件监听器一起使用?

转载 作者:行者123 更新时间:2023-12-04 16:27:04 24 4
gpt4 key购买 nike

我正在做这个元素,我需要滚动监听器和滚动捕捉,所以我可以在部分更改之间制作一些很酷的过渡效果。
我可以让这两个单独工作,但不能一起工作。滚动捕捉需要一个容器元素(main 元素)有一个高度,但是当我给它一个 height: 100% , JavaScript 滚动监听器停止工作。
我尝试了我所知道的一切,尝试更改其他容器的高度/溢出属性并尝试针对 body 之外的其他元素或 window .最好的解决方法是什么?
此处的代码段已调整为目前与监听器一起使用。如果您继续添加 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>

最佳答案

在另一个主题中,@lawrence-witt 说我必须将事件监听器添加到 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;
}
<!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>

关于javascript - 如何让 CSS 滚动捕捉与 JS 滚动事件监听器一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61761439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com