javascript 实现滚动显示的问题

n7taea2i  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(84)

我想在我的网页有各种类型的过渡。例如,我希望标题从上到下,而页面的最后一个元素从下到上。当元素出现在屏幕上时,我的JavaScript会添加显示的类。但是,如果元素向下移动(例如)-100px以返回到0 px与TranslateY,并且这个-100px将其推离屏幕,动画不会开始。我不知道问题是我的JavaScript还是TranslateY的使用。我不想使用外部库。
我的JavaScript代码:

// questa funzione serve a determinare se gli items osservati sono sullo schermo (utile per animazioni)
var elementiDaOsservare = document.querySelectorAll('.osservato');
var callback = function(items) {
    items.forEach((item) => {
        var position = item.target.getBoundingClientRect();
        if (item.isIntersecting) {
            item.target.classList.add("mostrato");
        } else if (position.top > 0) { // rimuove la classe mostrato solo se l'item si trova nella parte non visibile superiore dello schermo
            item.target.classList.remove("mostrato");
        }
    });
}
var observer = new IntersectionObserver(callback);
elementiDaOsservare.forEach((element) => {
    observer.observe(element);
});
2ledvvac

2ledvvac1#

这个问题比预期的更容易解决。我只是为过渡类型创建了各种情况,并删除了translateY的px距离:

const transitionT = document.querySelectorAll(".transitionT");
const transitionB = document.querySelectorAll(".transitionB");
const transitionL = document.querySelectorAll(".transitionL");
const transitionR = document.querySelectorAll(".transitionR");

function reveal() {
    transitionT.forEach(item => {
        var revealTop = item.getBoundingClientRect().top;
        var windowHeight = window.innerHeight;
        var revealPoint = 100;
        if (revealTop < windowHeight - revealPoint) item.classList.add("mostrato");
        else item.classList.remove("mostrato");
    });
    transitionB.forEach(item => {
        var revealTop = item.getBoundingClientRect().top;
        var windowHeight = window.innerHeight;
        var revealPoint = 100;
        if (revealTop < windowHeight + revealPoint) item.classList.add("mostrato");
        else item.classList.remove("mostrato");
    });
    transitionL.forEach(item => {
        var revealTop = item.getBoundingClientRect().top;
        var windowHeight = window.innerHeight;
        if (revealTop < windowHeight) item.classList.add("mostrato");
        else item.classList.remove("mostrato");
    });
    transitionR.forEach(item => {
        var revealTop = item.getBoundingClientRect().top;
        var windowHeight = window.innerHeight;
        if (revealTop < windowHeight) item.classList.add("mostrato");
        else item.classList.remove("mostrato");
    });
}

var observer = new IntersectionObserver(reveal);
transitionT.forEach((element) => {
    observer.observe(element);
});
transitionB.forEach((element) => {
    observer.observe(element);
});
transitionL.forEach((element) => {
    observer.observe(element);
});
transitionR.forEach((element) => {
    observer.observe(element);
});

相关问题