簡體   English   中英

在Vanilla JS的視口中切換CSS動畫

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

因此,我得到了用CSS制作的不同動畫,盡管問題是它們在頁面加載(當然)時立即開始。 我不想要這個。 Vanilla JavaScript中是否有辦法讓動畫僅在視口中啟動 我在很多地方都進行了搜索,但是我找到了需要使用的插件或jQuery。

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

這是您需要的代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM