我有一个onepager站点,我使用scrollmagic加上它所有必要的插件/库(和jQuery)来实现不同的效果,其中动画,钉扎,褪色过程等都是由滚动位置触发的。
我还使用它来动画滚动到页面上的锚点(从菜单和其他本地链接)-请参阅下面脚本的相应部分。
问题在于,当单击本地链接时,该脚本抑制了直接“跳转”到锚点的默认行为,显然,当通过直接链接或书签从外部访问页面时(如http://www.example.com/index.php#part3
),该脚本也抑制了这种默认行为,该书签将锚点附加到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);
}
}
});
(创建fiddle/codepen没有意义,因为问题在于从外部源调用原始URL)。
您可以尝试使用以下代码:
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(或页面)被加载,然后模拟用户单击nav项。
在我再读一遍你的问题之后,我不确定你是否希望你的页面加载在锚点中列出的元素的位置上,或者当来自外部源时滚动不工作?
如果滚动可以工作,但是你想在正确的位置显示页面,比如跳转,那么我建议两个解决方案:
a)在主体上使用CSS不透明度:0;
,在滚动完成后,将其设置回不透明度:1;
b)在加载ScrollMagic之前,尝试跳转到页面上的适当位置
好吧,假设卷轴魔法没有额外的功能,没有贴在这里,这会妨碍我的回答,你可以试试这个:
向链接添加要使用默认行为的data-attribute:
<a href="example.com/index.php#part3.php" data-default="true">
检查该数据属性是否存在,以及它是否在单击处理程序中返回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);
}
}
});