2017-09-26 92 views
-1

我期待有元素在您滾動到他們時淡入。趕上是我需要它在純香草的JavaScript ...絕對沒有jQuery。我在網上找到的所有東西都在jQuery中,這是一場鬥爭。我在爲我的動畫使用tweenMax。提前感謝您的幫助。元素淡入滾動PURE香草javascript

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

這是在'window.scroll'事件?如果是這樣,你會一遍又一遍地觸發你的動畫,這意味着它可能永遠沒有時間完成。 – arbuthnott

+0

如果您希望不透明度與滾動位置相關,您最終可能會去*真正*香草和動畫,而不需要像Tweenmax這樣的庫,它專注於基於時間的動畫(不基於滾動位置)。 – arbuthnott

回答

0

這裏我用CSS淡入/淡出。

在滾動我檢查是否元素是視口,如果是這樣,我添加類視圖,否則我刪除它。如果你想使它只是淡入,你可以改變選擇器以排除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; 
 
}