2017-02-22 39 views
1

所以我在CSS中制作了不同的动画,不过问题是当页面加载时(oncourse)它们立即启动。我不想要这个。有没有一种方法在香草JavaScript让动画只有当它在视口发射? 我在很多地方搜索过,但是我找到了一个我需要使用的插件或者jQuery。在视口中使用香草动作时切换CSS动画JS

HTML:

<div class="introduction"> 
    <h1>I can do the following for you:</h1> 
    <ul> 
     <li>Create a custommade, new website.</li> 
     <li>Code a PSD template into a working website.</li> 
     <li>Rework an outdated website.</li> 
     <li>Clean up messy code of a website.</li> 
    </ul> 
    </div> 

CSS:

@keyframes showOnLoad { 
    0% { 
     opacity: 0; 
    } 
    100% { 
     opacity: 1; 
    } 
} 

.introduction li { 
    list-style-type: none; 
    margin-bottom: 5px; 
    text-align: center; 
    opacity: 0; 
    -webkit-animation: showOnLoad; 
    animation: showOnLoad; 
    -webkit-animation-duration: 2s; 
    animation-duration: 2s; 
    -webkit-animation-fill-mode: forwards; 
    animation-fill-mode: forwards; 
} 

.introduction li:nth-child(2) { 
    -webkit-animation-delay: 1s; 
    animation-delay: 1s; 
} 

.introduction li:nth-child(3) { 
    -webkit-animation-delay: 2s; 
    animation-delay: 2s; 
} 

.introduction li:nth-child(4) { 
    -webkit-animation-delay: 3s; 
    animation-delay: 3s; 
} 

回答

2

这是你需要的代码。

window.addEventListener("scroll", onScroll); 

function onScroll() { 
    for (var item of document.querySelectorAll(".introduction li")) { 
    elementVisible(item); 
    } 
} 

function elementVisible(el) { 
    let top = el.offsetTop; 
    let height = el.offsetHeight; 
    let bottom = top + height; 

    let IsOverBottom = top > (window.pageYOffset + window.innerHeight); 
    let IsBeforeTop = bottom < window.pageYOffset; 

    if (!IsOverBottom && !IsBeforeTop) { 
    el.classList.add("show"); 
    } 
} 

,有点CSS

@keyframes slideIn { 
    0% { 
    opacity: 0; 
    transform: translateX(100%); 
    } 
    100% { 
    opacity: 1; 
    transform: translateX(0%); 
    } 
} 

.show { 
    animation: slideIn 5s ease-in-out; 
} 

这是一个基本的实现,但它让你更接近。

http://jsbin.com/hetapaj/1/edit?css,js,output