使用jQuery或JavaScript,当我滚动时,如何使动画文本逐一显示



我对我的网站标题有一个很棒的主意(在这种情况下,仅出于学习目的而不是Portofolio,公司网站等)。

这是我的想法:

有一个空白的标题,当我开始滚动时,一个单词出现时,就像刚被键入一样。

我该如何实现?

ps:

我只是在jQuery .scrolltop()方面尝试了效果,但没有得到它。它只是显示完整的句子,而不是像我想要的那样。

我搜索这个问题,但是,我的荒谬问题永远不会得到任何答案:)

<div id="text"> the text </div>

,因此您可以简单地进行一些计算,然后在滚动时逐一显示单词。

说明在代码上...

欢迎学习和快乐学习。

//Get the words from $text div and split it by spaces
var textArray = $('#text').text().split(' ');
// Clean inside html text to show after when scroll
$('#text').html(""); 
// Get the size of the array (how many words)
var textArraySize = textArray.length;
// Get the body height minus viewport and divide by how many words
// The reason to decrease the viewport is to show all the word when scroll hits the bottom.
// eg: (1000 - 200)/8 = 200, so a word will be show every 200px scrooled
var textShowAt = ($('body').height() - $(window).height() ) / textArray.length;
// Current word counter index
var textCurrent = 0;
$(window).scroll(function(){
    // Trigger the function when window is scrolled
    showWords();
});
function showWords(){
    //Return if all words is shown
    if(textCurrent >= textArraySize) return; 
    // Get how many pixels have scrolled from top 
    var scroll = $(window).scrollTop();
    if (
      // See if current scrolled size is higher then the current word
      scroll > (textShowAt * textCurrent)
    ) {
        // Append the text to the div
        $('#text').append(textArray[textCurrent] + ' ');
        // Increase textCurrent to show next array key (next word)
        textCurrent++;
    }
}
body {
  height: 1000px;
}
#text {
  position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">The text I want to show when scroll</div>

最新更新