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
});
添加回答
举报