【问题标题】:How to create a single one page navigation?如何创建单页导航?
【发布时间】:2015-05-09 17:01:45
【问题描述】:

有一段时间,我正在尝试编写一个不错的单页导航,滚动到右侧锚部分并更新他在菜单中的当前状态。

那么我需要哪种功能? - 处理点击事件的函数:当用户点击锚链接时,它应该滚动到该部分并更新菜单的当前状态。

  • 在滚动时摆脱活动状态的函数。

除此之外,我使用了一个固定的标题。所以标题的高度应该减去滚动位置,以避免粘性标题重叠内容。

想出了这个:

// An offset to push the content down from the top
    var offset = $('#header').outerHeight();




    $('#primary-navwrapper').find('li a[href^="#"]').click(function(event) { 

        // Current class switch
        $(this).removeClass("current");
        $(this).addClass("current");


        // The id of the section we want to go to.
        var anchorId = $(this).attr("href");


        // Our scroll target : the top position of 
        // the section that has the id referenced by our href.
        var target = $(anchorId).offset().top - offset;         
        //console.log(target);


        $('html, body').animate({ scrollTop: target }, 500, function () {
            window.location.hash = anchorId;        
        });


        // Prevent from default action to intitiate
        event.preventDefault();
        return false;

    });

function setActiveListElements(event) {

        // Get the offset of the window from the top of page
        var windowPos = $(window).scrollTop();

        $('nav li a[href^="#"]').each(function() { 
            var currentId = $(this);
            console.log(this);

            // if for active
            var target = currentId.attr("href");
            console.log(target);

            var offsetTop = target.position().top - offset;
            //var offsetBottom = offsetTop + target.height();

            if (target.length > 0) {
                console.log(target.position().top + target.height());
                if (target.position().top - offset <= windowPos && target.position().top + target.height() > windowPos) {
                    $('#primary-navwrapper li a').removeClass("current");
                    $(this).addClass("current");
                }
            }

        });

    }

它将滚动到它的位置,但不会更新当前状态。除此之外,我还尝试在滚动时更新 URL 中的哈希值,但不知道应该如何完成。

如果这可以更短和更好的编码,我也不反对,所以欢迎提出建议:)

【问题讨论】:

  • 你可以使用(我试图......但我得到错误......)而不是(我想要......)..之后我认为你会得到帮助..你的问题的答案很简单..但它只需要时间..祝你好运
  • 您考虑过使用fullPage.js 吗?

标签: jquery css


【解决方案1】:

查看这个名为 SMINT 的 jQuery 插件。我想这就是你所追求的。

http://www.outyear.co.uk/smint/

如果这是解决方案,请不要忘记通过单击勾选将此答案标记为正确答案。如果您想使用您当前的代码,那么我可以帮助您(只需在下面发表评论,我会为您提供帮助)但我真的认为这个插件是一条更简单的路线,但我不知道这是否是您所追求的效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 2018-04-28
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多