【问题标题】:simplify jquery Sticky menu scroll to function简化 jquery 粘性菜单滚动功能
【发布时间】:2014-08-14 09:55:31
【问题描述】:

我的单页网站上有一个水平导航,它在某个航路点变成了一个粘性导航。现在我创建了一个导航滚动条,看起来像这样

$(document).ready(function () {
    $("#button0").click(function() {
        $('html, body').animate({
            scrollTop: $("#ziel_top").offset().top
        }, 2000);
    });
    $("#button1").click(function() {
        $('html, body').animate({
            scrollTop: $("#ziel_1").offset().top-100
        }, 2000);
    });
    $("#button2").click(function() {
        $('html, body').animate({
            scrollTop: $("#ziel_2").offset().top-100
        }, 2000);
    });
    $("#button3").click(function() {
        $('html, body').animate({
            scrollTop: $("#ziel_3").offset().top-100
        }, 2000);
    });
    $("#button4").click(function() {
        $('html, body').animate({
            scrollTop: $("#ziel_4").offset().top-100
        }, 2000);
    });
});

现在我的问题是,有没有一种方法可以简化这个功能?任何想法表示赞赏

【问题讨论】:

    标签: jquery navigation jquery-animate scrollto sticky


    【解决方案1】:

    假设所有#buttons 实际上都是按钮:

    $(document).ready(function () {
        $("a[id^=button]").click(function() {
            var id=$(this).attr('id');
            id=id.substr(id.length-1);
            if(id==0){
                $('html, body').animate({
                    scrollTop: $("#ziel_top").offset().top
                }, 2000);
            }
            else{
                $('html, body').animate({
                    scrollTop: $("#ziel_"+id).offset().top
                }, 2000);
            }
        });
    });
    

    【讨论】:

    • 按钮实际上只是一个“a-tag”<li><a id="button0" href="#!">Start</a></li>
    • 如果它确实解决了您的问题,请您接受答案吗?
    【解决方案2】:

    这个?

    for (var i=0;i<5;i++)
    {
       $("#button" + i).click(function() {
          $('html, body').animate({
            scrollTop: $("#ziel_" + i).offset().top-100
          }, 2000);
        });
    }
    

    【讨论】:

    • 这看起来很整洁。谢谢!如果我添加超过 5 个链接/按钮,它也会自动工作吗?
    • 当然。对于任何数字。
    【解决方案3】:

    这是一个有点无耻的插件,但你可以使用jquery.localScroll。 您只需要一行 js,然后在 HTML 上设置导航(即使禁用 JS 也可以使用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-14
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多