简体   繁体   English

在Vanilla JS的视口中切换CSS动画

[英]CSS animations to toggle when in viewport with vanilla JS

So I have got different animations made in CSS, though the problem is that they start right away when the page loads (ofcourse). 因此,我得到了用CSS制作的不同动画,尽管问题是它们在页面加载(当然)时立即开始。 I do not want this though. 我不想要这个。 Is there a way in Vanilla JavaScript to get the animation to fire up only when it is in the viewport ? Vanilla JavaScript中是否有办法让动画仅在视口中启动 I have searched in a lot of places, but I either find a plugin I need to use or jQuery. 我在很多地方都进行了搜索,但是我找到了需要使用的插件或jQuery。

HTML: 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: 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;
}

This is the code you need. 这是您需要的代码。

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");
  }
}

And a bit of CSS 还有一点CSS

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

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

This is a basic implementation but it gets you closer. 这是一个基本的实现,但它使您更加接近。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM