Bootstrap scrollspy when accessing from another page

删除回忆录丶 提交于 2020-01-23 13:06:20

问题


Im trying to link to a specific section of my home page while maintaining a scroll spy feature.

With this code:

<li><a href="#sec1">About</a></li>

the scrollspy is functioning but if I try to access it from a page other than my home page it just adds "#sec1" to the current page's url, to no effect.

If I change it to:

<li><a href="/#sec1">About</a></li>

It takes me to the correct section on the home page, but the scrollspy function no longer works.

js code

$(function(){/* smooth scrolling for scroll to top */
     /* highlight the top nav as scrolling occurs */
     $('body').scrollspy({ target: '#navbar' })
});

Any ideas?


回答1:


you can try

$(document).ready(function(){
    var href = window.location.href; 
    var splitit = (href.split('#'))[1]; //split url to get sec1 name
    if(splitit !== "" || splitit !== "undefined"){
        $('html, body').animate({
            scrollTop: $('#'+splitit).offset().top
        }, 2000);
    }
});

this code will split the url to get sec1 or sec2 .... and then scroll to the div with id="sec1"

I mean if you redirect another page to www.website.com/anything#sec1 it will scroll the page to the div with id="sec1"

take a look at this DEMO

you can see this Jsffidle




回答2:


An alternative to the answer by @Mohamed-Yousef is to simulate the click on the links by doing

$(document).ready(function() {
    // workaround for deep link via anchor
    var stripped_url = window
                    .location
                    .toString()
                    .split("#");
    if (stripped_url.length > 1) {
        var activeId = "#nav-deep-" + stripped_url[1];
        $(activeId)[0].click();
    }
});

The jQuery selector requires the appropriate id on the link element like <a id="nav-deep-sec1" href="#sec1">About</a>.

And an even more elegant solution which avoids the extra IDs is to select the first link which points to the anchor by doing

$(document).ready(function() {
    // workaround for deep link via anchor
    var stripped_url = window
                    .location
                    .toString()
                    .split("#");
    if (stripped_url.length > 1) {
        $("a[href='#"+stripped_url[1]+"']")[0].click();
    }
});


来源:https://stackoverflow.com/questions/30721431/bootstrap-scrollspy-when-accessing-from-another-page

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