简体   繁体   中英

scroll to anchor + adjust for fixed menu at top

I've seen several Q&As on this but i cant seem to get any of them to work in my situation, such as: jQuery Smooth Page Anchor Transitions with position:fixed menu
:(

Page example: http://fpco-site.squarespace.com/familylife

As you scroll down the page, the main menu sticks/fixes to the top. there is also a dropdown tied into the fixed menu. inside the menu (and possibly other places on the page) i have regular links as well as anchor links. currently when the anchor links are clicked the menu & dropdown cover up the content when in the fixed position.

I need to get the jump to anchors to adjust to the menu and also the dropdown when open. it would be ideal for the content to animate up and down as it scrolls to the anchor and up and down as the dropdown opens and closes.

In case it matters, my anchors throughout the page are added via jquery.

I tried the following but there is something wrong in the code that breaks my dropdown menu:

    /* scrollTo */
    function scrollTo(id){
        $('html,body').animate({scrollTop: $(id).offset().top},'slow');
    };
    $('a[href^="#"]').click(function(){
        scrollTo($(this).attr('href'));
        return false;
    });

I figured if i could get that to work then i could then work on adding in the additional offest to account for the menu and then try to offset as the dropdown opens/closes. but i couldnt get this first idea to work ....

I was able to fix this in my situation by using some css to re-position my anchors. in my case the anchors are not applied to any visual element, so i could move them without it hurting anything. i used:

.anchor {
position: relative;
top: -160px;
height: 1px;
display: block;

}

i also told the dropdown to close when an anchor link in the dropdown is clicked. that way i didnt have to worry about wheather the dropdown was open or closed.

and now when i click to go to one of the anchors it lines up right under my fixed menu at the top :) there probably is a better way, but this works for me!~

Next to see if i can get it to animate to scroll to the anchor instead of jumping right to it. that would be nice :)

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