键入.js滚动时执行

typed.js execution when scrolled

本文关键字:执行 滚动 js 键入      更新时间:2023-09-26

我是初学者 - 只是说。

我正在尝试在线提供的不同.js文件,我发现键入.js。

但是,如果我有自己的网站,并且想要在滚动到页面的某个元素时执行键入的代码,该怎么办?

我得到了这个:

<script type="text/javascript" src="js/typed.js"></script>
<script>
    $(function(){
                    $("#typed").typed({
                        strings: ["Are you somehow interested?"],
                        typeSpeed: 30
                    });
                });
</script>

在我的 HTML 文件的末尾。

当我到达特定的div 或 h1 或其他什么时如何运行此代码?

是否有任何在线资源可以让我学习如何做到这一点?

谢谢!

首先有一个方法可以检查用户是否滚动到div,如下所示:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

然后将事件侦听器添加到窗口滚动,如下所示:

$(window).scroll(function() {    
    if(isScrolledIntoView($('#theTarget')))
    {
        //the div is now visible to user. here add your script
        $("#typed").typed({
                strings: ["Somehow interested?"],
                typeSpeed: 20
        });
    }    
});

试试这个:

var hasScrolledPast = false;
window.onscroll = function() {
    if (window.scrollTop > whereYouWantToScrollDownTo && !hasScrolledPast) {
        hasScrolledPast = true;
        // do your code here.
    }
};
<script>
    $(window).on('scroll', function() {
        var y_scroll_pos = window.pageYOffset;
        var scroll_pos_test = 1800;             // set to whatever you want it to be
        if(y_scroll_pos > scroll_pos_test) {
    //do stuff
            $(function(){
                $("#typed").typed({
                    strings: ["Zainteresowany?"],
                    typeSpeed: 20
                });

            });
            setTimeout(function() {
                $(function(){
                    $("#typed2").typed({
                    strings: ["Skontaktuj się z nami!"],
                    typeSpeed: 20
                });})}, 4000);
        }
    });
</script>

这解决了等待另一个函数执行的问题,但现在又出现了另一个问题。