gpt4 book ai didi

javascript - 元素淡入滚动 PURE vanilla javascript

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:47 24 4
gpt4 key购买 nike

我希望在您滚动到元素时淡入淡出。问题是我需要纯 vanilla javascript 中的它……绝对没有 jquery。我在网上找到的所有东西都在 jquery 中,这是一场斗争。我正在为我的动画使用 tweenMax。在此先感谢您的帮助。

    if(window.scrollY > 550){
TweenMax.staggerFromTo(newProduct, 1, {opacity:0}, {opacity:1}, 0.5);
}

最佳答案

这里我使用了 CSS 淡入/淡出。

在滚动时,我检查元素是否为视口(viewport),如果是,我添加类 inview,否则我删除它。如果你想让它只淡入,你可以改变选择器以排除 inview 类。

let section = document.createElement('section');
document.body.appendChild(section);
for (let x = 1; x <= 100; x ++) {
let d = document.createElement('div');
d.innerText = `Hello there div line ${x} of 100`;
section.appendChild(d);
}

function inView (el) {
var sb = section.getBoundingClientRect();
var eb = el.getBoundingClientRect();
return !((eb.top + eb.height < 0) || (eb.top > sb.height));
}

function updateInView() {
for (x of document.querySelectorAll('div')) {
if (inView(x)) x.classList.add('inview')
else x.classList.remove('inview');
}
}

section.onscroll = updateInView;

updateInView();
div {
opacity: 0.0;
transition: opacity 1s;
}

div.inview {
opacity: 1;
}

section {
width: 100%;
height: 100%;
overflow: auto;
background: black;
color: yellow;
}

html,
body {
height: 100%;
padding: 0;
margin: 0;
}

关于javascript - 元素淡入滚动 PURE vanilla javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46437376/

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