gpt4 book ai didi

javascript - CSS 滚动捕捉 API?

转载 作者:行者123 更新时间:2023-12-03 17:33:28 26 4
gpt4 key购买 nike

我很好奇...... CSS scroll-snap 属性是否有可以通过 JavaScript Hook 的 API(事件)?
我正在修改创建一个使用滚动捕捉在 100vh“幻灯片”之间移动的网站的想法。在每张幻灯片完成“滚动捕捉”后,我想触发一个动画。
我确信有一些巧妙的方法可以检查每张“幻灯片”,看看它是否占据了 100% 的视口(viewport),但这很糟糕。在滚动事件完成后触发函数会好得多。
这是一个 super 简单的例子:

$(document).ready(function() {
let slideNumber = $('.container > .slide').length;
if (slideNumber > 0) {
$('.container > .slide').each(function() {
$('#dotNav').append('<li><a href="#slide' + $(this).index() + '"></a></li>');
});
}

//DO SOMETHING AFTER SCROLL-SNAP IS COMPLETE.
});
html {
scroll-behavior: smooth;
}

body {
box-sizing: border-box;
scroll-snap-type: y mandatory;
}

.container {
width: 100%;
scroll-snap-type: y mandatory;
position: relative;
.slide {
height: 100vh;
width: 100%;
background: #cccccc;
scroll-snap-align: center;
display: flex;
justify-content: center;
align-items: center;
color: #000000;
&:nth-child(odd) {
background: blue;
h2 {
color: #ffffff;
}
}
h2 {
margin: 0;
font-size: 40px;
text-transform: uppercase;
}
}
ul#dotNav {
position: fixed;
top: 50%;
right: 20px;
list-style: none;
li {
width: 20px;
height: 20px;
margin-bottom: 10px;
cursor: pointer;
a {
display: block;
width: 100%;
height: 100%;
background: #ffffff;
border-radius: 50%;
}
}
li.active {
background: #000000;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="slide" id="slide0">
<h2>Slide 1</h2>
</div>
<div class="slide" id="slide1">
<h2>Slide 2</h2>
</div>
<div class="slide" id="slide2">
<h2>Slide 3</h2>
</div>
<ul id="dotNav">
</ul>
</div>

你可以看到它在这里工作:
https://codepen.io/trafficdaddy/pen/BMGBBg
希望有大神解答! :)

最佳答案

您可以使用 IntersectionObserver :

document.addEventListener("DOMContentLoaded", () => {
(function scrollSpy() {
const targets = document.querySelectorAll(".section"),
options = {
threshold: 0.5
};
// check if IntersectionObserver is supported
if ("IntersectionObserver" in window) {
(() => {
const inView = target => {
const interSecObs = new IntersectionObserver(entries => {
entries.forEach(entry => {
if(entry.isIntersecting) {
fireyourfunction();
}
});
}, options);
interSecObs.observe(target);
};
targets.forEach(inView);
})();
}
})();
});

关于javascript - CSS 滚动捕捉 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54797620/

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