2016-03-21 62 views
6

我有一个onepager网站,我使用scrollmagic加上所有必要的插件/库(和jQuery),用于动画,钉住,淡化过程等不同效果。由滚动位置触发。动画滚动脚本阻止从外部链接访问本地锚位置

我还将它用于动画滚动到页面上的定位点(从菜单和其他本地链接) - 请参阅以下脚本的相应部分。

的问题是,这个脚本抑制的“跳跃”直接到anchorpoint默认行为单击本地连接时,显然也当页面从外部通过直接链接或书签与锚访问附加到URL(如http://www.example.com/index.php#part3)。尽管单击本地链接时需要此行为,但显然会阻止浏览器在其他位置链接锚点时显示锚点位置。

有没有什么办法可以让浏览器直接显示锚定位置,当点击上面例子中的链接时?

var sm_controller_1 = new ScrollMagic.Controller(); 

sm_controller_1.scrollTo(function(anchor_id) { 
     TweenMax.to(window, 2.0, { 
       scrollTo: { 
         y: anchor_id 
         autoKill: true 
       }, 
       ease: Cubic.easeInOut 
     }); 
}); 
jQuery(document).on("click", "a[href^=#]", function(e) { 
     var id = jQuery(this).attr('href'); 
     if(jQuery(id).length > 0) { 
       e.preventDefault(); 
       sm_controller_1.scrollTo(id); 
       if (window.history && window.history.pushState) { 
         history.pushState("", document.title, id); 
       } 
     } 
}); 

(由于问题在于从外部源调用原始URL,所以创建小提琴/ codepen没有任何意义)。

回答

1

你可以尝试使用此代码:

jQuery(function ($) { 
    $(document).ready(function() {// if needed, use window.onload which fires after this event 
     if(window.location.hash) { 
      var hash = window.location.hash; 
      $('a[href=' + hash + ']').click(); 
     } 
    }); 
}); 

它会等到DOM(或页)被加载,然后模拟在导航项目的用户点击。

当我再次阅读您的问题后,我不再确定您是否希望将页面加载到锚点中列出的元素的位置,或者来自外部的滚动不起作用资源?

如果条幅是工作,但你想在正确的位置来显示页面,就像一个跳跃,然后我提出2个解决方案:

一)使用CSS opacity:0;对身体和滚动结束后,请将其重新设置为opacity:1; b)尝试跳到页面上的正确位置,然后加载ScrollMagic

+0

是的,这个工程!我只是使用了你发布的代码,而不是下面的建议,因为它已经按我想要的方式工作(即当页面加载URL中的锚点时直接跳到锚点)。非常感谢你! – Johannes

2

那么假设滚动魔法可是没有这里没有公布额外的功能,可能会得到我的回答的方式,你可以试试这个:

数据属性添加到您想要使用默认的行为你的链接:

<a href="example.com/index.php#part3.php" data-default="true"> 

检查数据属性存在,如果它确实return true在点击处理程序继续默认行为:

var sm_controller_1 = new ScrollMagic.Controller(); 

sm_controller_1.scrollTo(function(anchor_id) { 
     TweenMax.to(window, 2.0, { 
       scrollTo: { 
         y: anchor_id 
         autoKill: true 
       }, 
       ease: Cubic.easeInOut 
     }); 
}); 
jQuery(document).on("click", "a[href^=#]", function(e) { 
     if(e.currentTarget.dataset.default){ 
      return true; 
     } 
     var id = jQuery(this).attr('href'); 
     if(jQuery(id).length > 0) { 
       e.preventDefault(); 
       sm_controller_1.scrollTo(id); 
       if (window.history && window.history.pushState) { 
         history.pushState("", document.title, id); 
       } 
     } 
}); 
+0

感谢您的回答,并对我迟到的反应感到抱歉!问题是到锚点的链接都在导航菜单中,所以当我按照你的建议做时,所有链接的滚动动画都会被停用,导航链接直接跳到锚点而不滚动。所以这给了我相同的结果,如果我只是停用动画滚动,我不想要。我只能将它应用于我自己放置的其他网站上的链接(包括数据属性),但如果有人设置了书签或从我的网站复制了URL,它将不起作用。不过谢谢! – Johannes