简体   繁体   中英

Activate letter animation on scroll

I am trying to animate letters on scroll instead of triggering the animation every x second. I would like to divide the screen by the number of elements and each time you reach one of the division you trigger the letter animation.

For example if you scroll from 25% of the screen to 50% you will trigger the animation from the span number 2 to the span number 3 (see below for HTML). But if you scroll from 25% to 0% it would do the opposite and animate from the span 2 to the span 1.

Thank you for your help! And let me know if you need more details.

The code :

HTML

<div class="container">
<div class="text">
  <p>
    <span class="word">one</span>
    <span class="word">two</span>
    <span class="word">three</span>
    <span class="word">four</span>
  </p>
</div>
</div>

JQUERY

var words = document.getElementsByClassName('word');
var wordArray = [];
var currentWord = 0;

words[currentWord].style.opacity = 1;
for (var i = 0; i < words.length; i++) {
  splitLetters(words[i]);
}

function changeWord() {
  var cw = wordArray[currentWord];
  var nw = currentWord == words.length-1 ? wordArray[0] : wordArray[currentWord+1];
  for (var i = 0; i < cw.length; i++) {
    animateLetterOut(cw, i);
  }

  for (var i = 0; i < nw.length; i++) {
    nw[i].className = 'letter behind';
    nw[0].parentElement.style.opacity = 1;
    animateLetterIn(nw, i);
  }

  currentWord = (currentWord == wordArray.length-1) ? 0 : currentWord+1;
}

function animateLetterOut(cw, i) {
  setTimeout(function() {
        cw[i].className = 'letter out';
  }, i*80);
}

function animateLetterIn(nw, i) {
  setTimeout(function() {
        nw[i].className = 'letter in';
  }, 340+(i*80));
}

function splitLetters(word) {
  var content = word.innerHTML;
  word.innerHTML = '';
  var letters = [];
  for (var i = 0; i < content.length; i++) {
    var letter = document.createElement('span');
    letter.className = 'letter';
    letter.innerHTML = content.charAt(i);
    word.appendChild(letter);
    letters.push(letter);
  }

  wordArray.push(letters);
}

setInterval(changeWord, 4000);

So instead of

setInterval(changeWord, 4000);

it should be something like :

 $(window).scroll(function(){
      if($(window).scroll < $(document).height()/4){
         //the first span should have the class 'letter in';
      }else if($(window).scroll < ($(document).height()/4)*2){
          //the second span should have the class 'letter in';
      }
     //etc...
 });

The Codepen :

http://codepen.io/Leprince/pen/NrqmEJ

为什么不使用带有动画CSS或scrollmagic的jow插件(如wow.js)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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