简体   繁体   English

滚动时执行typed.js

[英]typed.js execution when scrolled

I'm a beginner - just saying. 我是初学者 - 只是说。

I'm trying out different .js files available online and I found typed.js. 我正在尝试在线提供不同的.js文件,我找到了typed.js。

But what if I have my own website and want to execute typed code when I scroll to a certain element of the page? 但是,当我滚动到页面的某个元素时,如果我有自己的网站并想要执行键入的代码,该怎么办?

I got this: 我懂了:

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

in the end of my HTML file. 在我的HTML文件的末尾。

How to run this code when I reach the specific div or h1 or whatever? 当我到达特定div或h1或其他什么时,如何运行此代码?

Is there any online source where I can learn how to do it? 有没有在线资源我可以学习如何做到这一点?

Thanks! 谢谢!

First of all have a method which will check if the user is scrolled to a div as following: 首先有一个方法,它将检查用户是否滚动到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));
}

Then add event listener to window scroll as following: 然后将事件监听器添加到窗口滚动,如下所示:

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

Try this: 尝试这个:

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>

This solved the problem of waiting for another function to execute, but now there is another problem. 这解决了等待执行另一个函数的问题,但现在还有另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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