как анимировать элемент css только когда он появляется в окне? - PullRequest
0 голосов
/ 19 февраля 2020

я знаю, что есть параллакс, но я хочу что-то еще, как на этом сайте joinhandshake.com

например, у меня есть этот код
html

<div class="black-div"></div>
   <div class="animated-div">
       <h1>Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit temporibus fuga sit quam fugit! Dignissimos quis qui, praesentium id nihil, aspernatur nostrum, dolores dolor molestiae error molestias ipsum ipsam at.</h1>
   </div>

css


.black-div {
    background-color: black;
    height: 130vh;
}
 @keyframes rotate-scale-up {
    0% {
      transform: scale(1) rotateZ(0);
    }
    50% {
      transform: scale(2) rotateZ(180deg);
    }
    100% {
      transform: scale(1) rotateZ(360deg);
    }
  }
  .animated-div {
    animation: rotate-scale-up 0.65s linear both;
}

проблема в том, что когда я загружаю страницу, текст анимируется, так как я могу предотвратить это?

Ответы [ 2 ]

1 голос
/ 19 февраля 2020

Чтобы проверить, виден ли элемент, используйте API-интерфейс Intersection Observer . Этот API построен именно для этой цели и практически не требует вычислений, только проверка со значением isIntersecting, чтобы увидеть, вошел ли элемент в представление.

IntersectionObserverIn использует функцию обратного вызова сделать что-то, когда элемент вошел или покинул вид. В этой функции вы можете указать, что должно произойти, когда это произойдет.

Я сделал фрагмент с примером того, как он работает и как вы можете его реализовать.

/**
 * What to do when an item enters the screen
 * If it is in the screen, isIntersecting will be true.
 * Add a class when it is.
 */
const intersectionCallback = (entries) => {
  for (const entry of entries) { // Loop over all elements that either enter or exit the view.
    if (entry.isIntersecting) { // This is true when the element is in view.
      entry.target.classList.add('show'); // Add a class.
    }
  }
}

/**
 * Create a observer and use the instersectionCallback as 
 * the instructions for what to do when an element enters
 * or leaves the view
 */
const observer = new IntersectionObserver(intersectionCallback);

/**
 * Get all .item elements and loop over them.
 * Observe each individual item.
 */
const items = document.querySelectorAll('.item');
for (const item of items) {
  observer.observe(item);
}
.item {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  height: 200px;
  width: 100%;
  margin-bottom: 20px;
  opacity: 0;
  transition: opacity 1s ease-out;
}

.item:nth-of-type(odd) {
  background-color: #333;
}

.item:nth-of-type(even) {
  background-color: #111;
}

.item.show {
  opacity: 1;
}
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
<div class="item">Hello</div>
0 голосов
/ 19 февраля 2020

Тогда для элемента полной загрузки страницы используйте jQuery.

  setTimeout(function () {
  $("div").addClass("black-div").delay(2000).fadeIn(); 
  });
...