1 回答

TA貢獻1827條經驗 獲得超8個贊
如果你不想要一個圖書館,你可以這樣做。(由其他貢獻者拼湊而成,ty)您可以為不同的選擇器添加不同的效果。當設置的元素百分比可見時動畫觸發一次(isInViewport - 第二個參數,當前設置為 35%)。只觸發一次。
//every element needs to have a "hidden" class, ie. "visability:hidden" if starting state is hidden (fad-in effects and similar)
var elemList = {elements:[ //add elements and animations here
{elem:"#home-description", animation:"element-animation"},
{elem:".nav-item",animation:"slide-in-top"}
]};
var isInViewport = function(el, percentVisible) {
let
rect = el.getBoundingClientRect(),
windowHeight = (window.innerHeight || document.documentElement.clientHeight);
return !(
Math.floor(100 - (((rect.top >= 0 ? 0 : rect.top) / +-(rect.height / 1)) * 100)) < percentVisible ||
Math.floor(100 - ((rect.bottom - windowHeight) / rect.height) * 100) < percentVisible
)
};
function check(){
var eArray = elemList.elements;
if (eArray.length >= 1){
eArray.forEach( function(e,i){
if (e.elem){ //check if empty
let el = document.querySelectorAll(e.elem);
if (el.length >= 1){
el.forEach( function(x,y){
if (isInViewport(x,35)){
x.classList.remove("hidden") //remove this if element should be visible
x.classList.add(e.animation)
eArray.splice(i, 1)
}
})
}
}
})
}
}
window.addEventListener('load', function () {
check();
document.addEventListener('scroll', function () {
check();
})
}, {
passive: true
});
添加回答
舉報