动画滚动脚本可防止从外部链接访问本地锚点位置

时间:2016-03-21 17:27:59

标签: javascript jquery html scroll scrollmagic

我有一个onepager网站,我使用 scrollmagic 加上所有必要的插件/库(和jQuery),用于不同的效果,其中动画,固定,淡入淡出过程等由滚动位置触发。

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

问题是这个脚本会抑制"跳跃"的默认行为。单击本地链接时直接指向锚点,并且显然也是当通过直接链接或带有附加到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)。

2 个答案:

答案 0 :(得分: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);
                }
        }
});

答案 1 :(得分: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个解决方案:

a)在正文上使用CSS opacity:0;,滚动完成后,将其设置回opacity:1; b)在加载ScrollMagic之前尝试跳到页面上的适当位置

相关问题