6

我在浏览器顶部有一个静态菜单,当有人点击链接时,菜单位于文本上方。

我这样做了,但scrollTop不起作用:

jQuery(document).ready(function () {
    $('a[href^="#"]').click(function()
    {
        var sHref = this.href.split("#"); 
        $("#"+sHref[1]).scrollTop($("#"+sHref[1]).scrollTop() + 100); // <- does not work
    });
});
4

1 回答 1

8

您不需要拆分href属性,因为它已经包含#(您在选择器中检查)。

$(function() {
    // Desired offset, in pixels
    var offset = 100;
    // Desired time to scroll, in milliseconds
    var scrollTime = 500;

    $('a[href^="#"]').click(function() {
        // Need both `html` and `body` for full browser support
        $("html, body").animate({
            scrollTop: $( $(this).attr("href") ).offset().top + offset 
        }, scrollTime);

        // Prevent the jump/flash
        return false;
    });
});

此外,为了使编辑更容易,您可以将偏移量从 更改100$('menu_element').height()。如果您更改了菜单,则无需编辑 JS 即可使用。

于 2013-10-31T03:53:02.657 回答