![](/img/trans.png)
[英]toggleClass to reveal hidden div - add animation and window scroll?
[英]How to add animation to the active div on window scroll?
我的頁面中有多個 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>
所以我在這里所做的是,首先我檢查了滾動事件,然后決定滾動實際上是向上還是向下。 一旦我確定我是向上還是向下滾動,我就分別添加了這些類。 對於不可見的類,我正在設置樣式 transform: 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
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.