我正在实现一个没有jquery或js插件的项目,我正在尝试创建一个像waypoints.js库这样的自定义脚本。我想要做的是当我到达一个元素(其高度的一半)时,我想添加一个类(带有css动画)并同时删除一个类(具有不透明度0的类)。我已经做了很多工作但是有一些东西丢失了。首先,如果我快速滚动到页面底部,那么类更改就不会发生,因此当我滚动向上时会发生这种情况,这是我不想要的。其次,如果我刷新页面然后添加初始类(具有不透明度0的那个),即使我在页面的中间位置刷新而且我应该显示这些项目。
HTML:
<section id="about" class="section">
<div class="section__square waypoint white" data-classToAdd="black" data-classToRemove="white"></div>
</section>
<section id="portfolio" class="section">
<div class="section__square waypoint white" data-classToAdd="black" data-classToRemove="white"></div>
</section>
<section id="contact" class="section">
<div class="section__square waypoint white" data-classToAdd="black" data-classToRemove="white"></div>
</section>
JS:
const waypoints = document.querySelectorAll('.waypoint');
function checkpoint() {
waypoints.forEach(waypoint => {
//halfway through the element
const addClassAt = (window.scrollY + window.innerHeight) - waypoint.clientHeight / 2;
const isHalfShown = addClassAt > waypoint.offsetTop;
const elementBottom = waypoint.offsetTop + waypoint.clientHeight;
const isNotScrollPast = (window.scrollY + window.innerHeight) <= elementBottom;
if (isHalfShown && isNotScrollPast) {
waypoint.classList.remove(waypoint.getAttribute('data-classToRemove'));
waypoint.classList.add(waypoint.getAttribute('data-classToAdd'));
}
});
}
window.addEventListener("scroll", checkpoint);
这是一个codepen: https://codepen.io/anon/pen/XEgwvL 让我们说白色类是不透明度:0和黑色是动画显示。 提前致谢
答案 0 :(得分:0)
这是我的解决方案:
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: el.left + window.scrollX,
top: el.top + window.scrollY
}
}
const waypoints = document.querySelectorAll('.waypoint');
function checkpoint() {
waypoints.forEach(waypoint => {
//halfway through the element
const addClassAt = (window.scrollY + window.innerHeight) - waypoint.clientHeight / 2;
const isHalfShown = addClassAt > waypoint.offsetTop;
const elementBottom = waypoint.offsetTop + waypoint.clientHeight;
const isGoThrough = window.scrollY > (getOffset(waypoint).top + waypoint.clientHeight / 2 ) ;
if (isHalfShown && isGoThrough) {
waypoint.classList.remove(waypoint.getAttribute('data-classToRemove'));
waypoint.classList.add(waypoint.getAttribute('data-classToAdd'));
}
});
}
window.addEventListener("scroll", checkpoint);
滚动此元素时添加类。 您可以查看我的codepen:https://codepen.io/titan_dl_1904/pen/dmZvXW