anchor linking to a certain position of the page

前端 未结 7 2176
渐次进展
渐次进展 2021-01-06 18:06

I have an anchor link which links to another page. When it is clicked, by default it goes to the top of the next page. I want it brought to a certain position of the page. H

7条回答
  •  我在风中等你
    2021-01-06 18:24

    OK, so this answer is very specific to your problem.

    The reason none of the other solutions worked is that your div elements that would match the anchor are hidden when the page loads.

    To prove this out, click on of your links on the home page, and see it not work. Then change the hash from #whatever to #bgaboutbody and you will see it work properly.

    So, using something like this will make it work for you. Basically, if there is a hash, it will animate down to the correct spot. Put this in a script block at the very bottom of your page (right above the tag)

    window.setTimeout(function(){
        if(window.location.hash){
            var $target  = $(window.location.hash).closest("#bgaboutbody");
            if($target.length)
                $('html, body').animate({scrollTop: $target.offset().top}, 1000);
        }
    }, 100);
    

    Learn to use fallbacks:

    It is always better to make sure your content will load without JavaScript on a sales site like this. (In a web app I feel that is a different discussion). I would recommend using the solution I gave you to this question where you add a js class to the html element in the of the page. Then scope your CSS like this:

    .js #contact, .js #about, etc { display:none }
    

    So it will only be hidden if JS is present. Additionally, since this solution is also using JavaScript its important they are visible if JS is disabled so it still works.

提交回复
热议问题