我的页面中有多个 div。该 div 包含大小和颜色。向下滚动时,屏幕可见的 div 应向上移动,向上滚动时,应返回到其原始位置。
这是迄今为止我尝试过的代码。使用此代码,当我向下滚动时,div 向上移动,但当我向上滚动时,div 不会向下移动。有人可以帮我吗?
function isElementInViewport(el) {
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top <= 0 &&
rect.bottom >= 0) ||
(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight)) ||
(rect.top >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
);
}
window.addEventListener('scroll', function(e) {
winScrollTop = $(this).scrollTop();
var elementsToShow = document.querySelectorAll('.rectangle');
Array.prototype.forEach.call(elementsToShow, function(element) {
if (isElementInViewport(element)) {
element.classList.add('is-visible');
} else {
element.classList.remove('is-visible');
}
});
});
.rectangle {
background-color: red;
height: 444px;
width: 100px;
/* margin-top: -98px; */
z-index: -30;
transition: 0.5s;
transform: translateY(-98px);
margin-bottom: 25px;
}
.is-visible {
transform: translateY(-250px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rectangle"></div>
<div class="rectangle"></div>
<div class="rectangle"></div>
<div class="rectangle"></div>
最佳答案
所以我在这里所做的是,首先检查滚动事件,然后确定滚动实际上是向上还是向下。一旦我确定了我是向上还是向下滚动,我就分别添加了这些类。对于不可见的类,我设置样式转换:translateY(0px),它只是将元素返回到其默认位置。
.not-visible{
transform: translateY(0px);
}
var lastScrollTop= 0;
window.addEventListener('scroll', function(e) {
winScrollTop = $(this).scrollTop();
var st = window.pageYOffset || document.documentElement.scrollTop; // Credits:
var elementsToShow = document.querySelectorAll('.rectangle');
if (st > lastScrollTop){ // If st is greater than lastscrollTop then it is downward
console.log("down");
// then check if elemetnts are in view
Array.prototype.forEach.call(elementsToShow, function(element) {
if (isElementInViewport(element)) {
element.classList.remove('not-visible'); // remove class notvisible if any
element.classList.add('is-visible'); // Add class isvisible
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
});
} else {
console.log("up");
Array.prototype.forEach.call(elementsToShow, function(element) {
if (isElementInViewport(element)) {
// Remove class isvisible and add class not visible to move the element to default place
element.classList.remove('is-visible');
element.classList.add('not-visible');
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
});
}
});
关于javascript - 如何在窗口滚动时向事件 div 添加动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579489/