animated scrolling script prevents local anchor positions to be accessed from external links

余生颓废 提交于 2019-11-28 13:39:19

You can try and use this code:

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();
        }
    });
});

It will wait till the DOM (or the page) is loaded and then simulate the user click on the nav item.

After I've read your question one more time, I am not sure anymore if you want your page loaded on the position of the element which is listed in the anchor or the scroll wasn't working when coming from an external source?

If the scroll was working but you wanted to display the page at the right place, like a jump, then I propose 2 solutions:

a) use the CSS opacity:0; on the body and after the scroll is finished, set it back to opacity:1; b) try to jump on the proper place on the page before you load ScrollMagic

Well assuming scroll magic doesnt have extra functionality that is not posted here that would get in the way of my answer you could try this:

Add a data-attribute to your links which you want to use default behavior:

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

Check if that data attribute exists and if it does return true in your click handler to continue with the default behavior:

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);
                }
        }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!