我试图在滚动上设置动画,而不是每隔x秒触发一次动画。我想将屏幕除以元素的数量,每当你到达其中一个分区时,你就会触发字母动画。
例如,如果从屏幕的25%滚动到50%,则会触发从范围编号2到范围编号3的动画(请参阅下面的HTML)。但是,如果从25%滚动到0%,它将执行相反的操作,并从范围2到范围1进行动画处理。
感谢您的帮助! 如果您需要更多详细信息,请与我们联系。
代码:
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);
所以而不是
setInterval(changeWord, 4000);
应该是这样的:
$(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...
});
Codepen:
答案 0 :(得分:0)
为什么不使用jquery插件,例如wow.js和animate css或scrollmagic