简体   繁体   中英

Using switch statement to scroll to anchor from another page

I am having trouble getting my script to do any scroll actions for some reason. I am using a switch statement to determine which link was clicked (the link is on my nav, so you are coming from another page entirely), then I want to have the page scrolled to the top of the page (and eventually scroll smoothly down to the anchor again). For some reason my console log statement is firing but the page is not scrolling to the top. When I type window.scrollTo(0, 0); into the console though the page scrolls up...here is my script, any help is appreciated.

var URL = window.location.href;
var baseURL = window.location.protocol+'//'+window.location.host+window.location.pathname;

switch(URL) {
    case baseURL+'#skills':
        window.scrollTo(0, 0);
        console.log('you are on skills');       
        break;
    case baseURL+'#experience':
        window.scrollTo(0, 0);
        console.log('you are on expereince');       
        break;
    case baseURL+'#works':
        window.scrollTo(0, 0);
        console.log('you are on works');        
        break;
}

Actually I got the answer, instead of applying a name to my anchor links (so that the browser jumps directly to the link) I just applied a class to each of the links and scrolled to them once the page had loaded.

$(window).on("load", function () {
     urlHash = window.location.href.split("#")[1];
    $('html,body').animate({
        scrollTop: $('.' + urlHash).offset().top
    }, 1000);
});

Where my links would look like this on the HTML side.

<a class="works">Portfolio</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM