如何在滚动上逐个字母加载文本

How to load text letter by letter on scroll

本文关键字:加载 文本 滚动      更新时间:2023-09-26

大家好,我试图加载我的h2文本一次,当我滚动到div和h2的内容必须像打字机一样逐个字母加载。我已经用这种方法试过了,但没有用。你们知道吗?

$(window).scroll( function(){   
        $('.inner h2').each(function (i){          
            var header = $(this);
            var header_content = header.html();
            var content = new Array();
            content[i] = header_content;
            position = new Array();
            position[i] = $(this).position().top;
            console.log(content[i]+' pos '+position);     
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            if( bottom_of_window > position[i] ){
                var arrayTitle = content[i].split('');
                var i = 0;              
                var interval = setInterval(function(){
                if (i > arrayTitle.length) 
                {
                  header.html(content[i]);        // wipe out the <span> tags
                  clearInterval(interval);
                } 
                else
                {
                  $('<span>')
                    .html(arrayTitle[i])
                    .appendTo(header)
                    .hide()
                    .fadeIn(50);                    
                    i++;      
                }
                }, 50);
            }            
        }); 
    });

Jsfiddle

我的看法是:http://jsfiddle.net/Sladkoff/73TDB/

我将滚动事件处理程序放在每个函数中。这样,每个元素都有自己的"实例"变量和处理程序。它需要一些更多的调整,但这可能会帮助你作为一个基础。

这对我来说没什么意义:

我没有附加span,因为我没有真正从你的描述/代码中理解你到底想要实现什么。

如果这不是你想要的,那么至少我清理了一点:)

// I would have just left a comment if I could.