gpt4 book ai didi

javascript - 如果从顶部和底部滚动到 View 中,则向元素添加不同的类

转载 作者:行者123 更新时间:2023-12-01 04:32:49 26 4
gpt4 key购买 nike

我有一段代码,如果从顶部和底部滚动到 View 中,则会向元素添加不同的 css 类。

为了实现这一点,代码识别四种状态:

  1. 从顶部滚动到 View (添加“inview-top”类)
  2. 从底部滚动到 View (添加“inview-bottom”类)
  3. 滚动到顶部 View 之外(添加“outview-top”类)
  4. 滚动到底部 View 之外(添加“outview-top”类)

在添加 outview 类时,它还会删除所有 inview 类,反之亦然。

我的问题是它使用 Intersection Observer API实现这一目标似乎非常不可靠。当观察到的元素仅位于彼此下方时,它可以完美地工作,但是当它们在一行中彼此相邻时,它就会变得非常错误。很多时候它根本不触发回调。在我的示例中,这意味着大多数 DIV 保持不可见,即使它们一旦滚动到 View 中就应该变得可见。

这就是为什么我想知道一种可靠的方法来达到预期的结果。无论页面上有多少元素,无论它们放置在何处,它都应该表现良好。

你可以试试我的代码on jsFiddle或者在这里查看:

const config = {
root: null,
rootMargin: '0px',
threshold: [0.15, 0.2, 0.25, 0.3]
};

let previousY = 0;
let previousRatio = 0;


let observer = new IntersectionObserver(function(entries) {
entries.forEach(entry => {
const currentY = entry.boundingClientRect.y
const currentRatio = entry.intersectionRatio
const isIntersecting = entry.isIntersecting
const element = entry.target;

element.classList.remove("outview-top", "inview-top", "inview-bottom", "outview-bottom");
// Scrolling up
if (currentY < previousY) {
const className = (currentRatio >= previousRatio) ? "inview-top" : "outview-top";
element.classList.add(className);

// Scrolling down
} else if (currentY > previousY) {
const className = (currentRatio <= previousRatio) ? "outview-bottom" : "inview-bottom";
element.classList.add(className);
}

previousY = currentY
previousRatio = currentRatio
})
}, config);

const viewbox = document.querySelectorAll('.viewme');
viewbox.forEach(image => {
observer.observe(image);
});
body {
text-align: center;
}
.hi {
padding: 40vh 0;
background: lightblue;
}
.box {
width: 23%; /* change this to 100% and it works fine */
height: 40vh;
margin-bottom: 10px;
background: blue;
display: inline-block;
}

.viewme {
opacity: 0;
transform: translateY(20px);
transition: all .3s ease;
}

.inview-top, .inview-bottom {
opacity: 1;
transform: translateY(0);
}

.outview-top {
opacity: 0;
transform: translateY(-20px);
}
.outview-bottom {
opacity: 0;
transform: translateY(20px);
}
<p class="hi">There should always be four blue boxes in one row. Scroll down and back up</p>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>

最佳答案

问题出在 previousYpreviousRatio 变量上。它们正在被每一个元素所改变。因此,当迭代处理当前元素时,变量已经被前一个元素改变。

解决这个问题的方法是将两个变量都更改为数组,并将每个条目的值添加到其中。这样每个修改都与其他元素分开。

我将类更改为数据属性。它提供了更可靠的交换和清理。

使用 IntersectionObserver:

解决方法是计算与root top相关的div top和与rootbottom相关的div的bottom。这样您就不需要添加全局变量或数组来存储以前的位置或口粮。

const config = {
// Add root here so rootBounds in entry object is not null
root: document,
// Margin to when element should take action
rootMargin: '-50px',
// Fine tune threshold. The callback will fired 30 times during intersection. You can change it to any number yout want
threshold: [...Array(30).keys()].map(x => x / 29)
};

let observer = new IntersectionObserver(function(entries, observer) {

entries.forEach((entry, index) => {
const element = entry.target;

// Get root elemenet (document) coords
const rootTop = entry.rootBounds.top;
const rootBottom = entry.rootBounds.height;

// Get div coords
const topBound = entry.boundingClientRect.top - 50; // -50 to count for the margine in config
const bottomBound = entry.boundingClientRect.bottom;

let className;

// Do calculations to get class names
if (topBound < rootTop && bottomBound < rootTop) {
className = "outview-top";
} else if (topBound > rootBottom) {
className = "outview-bottom";
} else if (topBound < rootBottom && bottomBound > rootBottom) {
className = "inview-bottom";
} else if (topBound < rootTop && bottomBound > rootTop) {
className = "inview-top";
}
element.setAttribute('data-view', className);

})
}, config);

const viewbox = document.querySelectorAll('.viewme');
viewbox.forEach(image => {
observer.observe(image);
});
body {
text-align: center;
}

.margins {
position: fixed;
top: 50px;
bottom: 50px;
border-top: 2px dashed;
border-bottom: 2px dashed;
z-index: 1;
left: 0;
width: 100%;
pointer-events: none;
}

.hi {
padding: 40vh 0;
background: lightgray;
}

.box {
width: 23%;
/* change this to 100% and it works fine */
height: 40vh;
margin-bottom: 10px;
background: lightblue;
display: inline-block;
}

.viewme {
opacity: 0;
transform: translateY(20px);
transition: all .3s ease;
}

.viewme[data-view='inview-top'],
.viewme[data-view='inview-bottom'] {
opacity: 1;
transform: translateY(0);
}

.viewme[data-view='outview-top'] {
opacity: 0;
transform: translateY(-20px);
}

.viewme[data-view='outview-bottom'] {
opacity: 0;
transform: translateY(20px);
}
<p class="hi">There should always be four blue boxes in one row. Scroll down and back up</p>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>

<div class='margins'>

</div>

替代解决方案:

使用scroll事件。这种方法比 IntersectionObserver 更可靠并且更简单。但是,它可能会导致一些滞后(对于大量元素)。

const viewbox = document.querySelectorAll('.viewme');
const containerHeight = window.innerHeight;

window.addEventListener("scroll", function(e) {
const direction = (this.oldScroll > this.scrollY) ? "up" : "down";
this.oldScroll = this.scrollY;

viewbox.forEach((element, index) => {
element.viewName = element.viewName || "";
const rect = element.getBoundingClientRect();
const top = rect.top + 50;
const bottom = rect.bottom - 50;

if (direction == "down") {
if (top > 0 && top < containerHeight)
element.viewName = "inview-bottom";
else if (top < 0 && bottom < 0)
element.viewName = "outview-top";

} else {
if (top > containerHeight)
element.viewName = "outview-bottom";
else if (top < 0 && bottom > 0)
element.viewName = "inview-top";
}
element.setAttribute('data-view', element.viewName);
});
});

// Trigger scroll on initial load
window.dispatchEvent(new Event('scroll'));
body {
text-align: center;
}

.margins {
position: fixed;
top: 50px;
bottom: 50px;
border-top: 2px dashed;
border-bottom: 2px dashed;
z-index: 1;
left: 0;
width: 100%;
pointer-events: none;
}

.hi {
padding: 40vh 0;
background: lightgray;
}

.box {
width: 23%;
/* change this to 100% and it works fine */
height: 40vh;
margin-bottom: 10px;
background: lightblue;
display: inline-block;
}

.viewme {
opacity: 0;
transform: translateY(20px);
transition: all .3s ease;
}

.viewme[data-view='inview-top'],
.viewme[data-view='inview-bottom'] {
opacity: 1;
transform: translateY(0);
}

.viewme[data-view='outview-top'] {
opacity: 0;
transform: translateY(-20px);
}

.viewme[data-view='outview-bottom'] {
opacity: 0;
transform: translateY(20px);
}
<p class="hi">There should always be four blue boxes in one row. Scroll down and back up</p>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>
<div class="box viewme"></div>

<div class='margins'>

</div>

关于javascript - 如果从顶部和底部滚动到 View 中,则向元素添加不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61908478/

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