简体   繁体   中英

jQuery ScrollTo function scrolling past element id

I am designing a simple, one-page website that uses a navigation menu at the top to scroll to various points of the page. As of recently, I am having trouble scrolling to one of the pages. When I attempt to scroll to my "About" section, the jQuery function scrolls past the beginning of the section and down to the top of the first element inside the section.

However, all I need to do is simply add a border to the section( border: 2px dashed yellow ), and the function correctly scrolls to the top of the "About" section (and displays the border at the very top).

Here is the jQuery function. I know that it is correct, because the menus scrolls normally to the "Contact" section that is directly below on the page.

function scrollTo(element)
{
    var tag = $("#" + element + "");
    $('html, body').animate({scrollTop: tag.offset().top}, 500);
}

And my HTML for the Menu Bar...

<nav id="menuBar">
    <ul>
        <li><a href="#">Home</a>
        </li><li><a href="#" onclick="alert('This page is still under ' +
                    'construction. Sorry!')">Products</a>
        </li><li><a href="#" onclick="alert('This page is still under ' +
                    'construction. Sorry!')">Projects</a>
        </li><li><a href="#" onclick="scrollTo('aboutSection')">
                About Me</a>
        </li><li><a href="#" onclick="scrollTo('contactSection')">
                Contact Me</a></li>
    </ul>
</nav>


And then HTML for the About section

#aboutSection
{
    /* Testing purposes */
    border: 2px dashed yellow;
}

And the CSS that makes it function correctly...

 #aboutSection { /* Testing purposes */ border: 2px dashed yellow; } 

Once again, when I remove this last line of CSS, the jQuery function scrolls past the top of the <section> with id="aboutSection" , and down to the top of the next element.


Example of About section

错误示例

Is there an easy way to fix this? Let me know if I need to include anything else.

From your included picture, you are pointing the "Should scroll to here" arrow at the bottom of the menubar / header, not the top of the window. This leads me to believe this could be an issue with the menubar -- the top of your window is probably being set at the correct height, but the menubar is covering it up. What you want to do is scroll to the top of the section minus the menubar height , so that the point where you want the top to be is at the bottom of the navbar instead of at the top of the page:

var tag = $("#" + element + "");
var navHeight = parseInt($('#menuBar').css('height')); 
$('html, body').animate({scrollTop: tag.offset().top - navHeight}, 500);

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