另一个脚本完成后jQuery fire函数

时间:2016-09-01 14:31:54

标签: javascript jquery

我有一个打字动画插件需要几秒钟才能运行。在那里,显示一个按钮。我还有一个功能,可以平滑滚动到锚链接并从URL中剥离锚点。我加载他们在文档准备就绪时键入脚本,并在窗口加载时滚动功能。我遇到的问题是,当点击输入插件中的锚链接时,不会触发滚动功能。我也尝试在输入插件后立即调用滚动功能。我的代码目前看起来像这样。

function anchorLinks() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top -1
          }, 500);
          return false;
        }
      }
    });
}; 


$(window).load(function(){
  anchorLinks();
});

然后......

$(document).ready(function(){
  $('#msg').typeIt({
      speed: 50,
      breakLines: false,
      autoStart: false,
      cursor: false,
      startDelay: 2000
  })
  .tiType('Hi!')
  .tiPause(1500)
  .tiDelete()
  .tiType('I\'m Sandra Willford, and welcome to TENDesign.')
  .tiPause(1500)
  .tiDelete()
  .tiType('Looking for a designer that has bright ideas for your brand?')
  .tiPause(1500)
  .tiDelete()
  .tiType('Well congratulations, you\'ve landed in the right spot :)')
  .tiPause(1500)
  .tiDelete()
  .tiType('I specialize in fresh and innovative digital, website & branding designs.')
  .tiPause(1500)
  .tiDelete()
  .tiType('Are you ready to take your brand to the next level?')
  .tiPause(1500)
  .tiDelete()
  .tiType('<a href="#start">OMG, Yes I am!...Show me more.</a>');
  anchorLinks();
});

建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

我认为你需要这样的东西。未经测试:

$(document).on('click', 'a[href*=#]:not([href=#])', function (e) {
    e.preventDefault(); //<!-- use this instead return false. 
    //Return false is triggering preventDefault and stopPropagation also.
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html,body').animate({
                scrollTop: target.offset().top - 1
            }, 500);
        }
    }
});
  • 您无需从代码中调用该函数,因为我将其删除了。

  • 对动态加载的元素使用$(document).on()

  • 请勿在函数内使用document.ready

  • 如果真的不是必需的话,请不要在事件内部附加事件处理程序。取而代之的是,在需要的位置使用off()

相关问题