【问题标题】:typed.js execution when scrolledtyped.js 滚动时执行
【发布时间】:2015-10-11 12:38:59
【问题描述】:

我是一个初学者 - 只是说。

我正在尝试在线提供的不同 .js 文件,我找到了 typed.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 或其他什么时如何运行此代码?

是否有任何在线资源可以让我学习如何操作?

谢谢!

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

首先有一个方法可以检查用户是否滚动到一个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
        });
    }    
});

【讨论】:

    【解决方案2】:

    试试这个:

    var hasScrolledPast = false;
    window.onscroll = function() {
        if (window.scrollTop > whereYouWantToScrollDownTo && !hasScrolledPast) {
            hasScrolledPast = true;
            // do your code here.
        }
    };
    

    【讨论】:

      【解决方案3】:
      <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>
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-16
        • 1970-01-01
        • 2020-09-27
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多