javascript - 当用户通过导航向下滚动时显示部分

标签 javascript jquery

我有一个页面,其中包含许多部分,当用户滚动页面时会显示这些部分。这是完整的工作代码。

/**
    * Reveal Sections as the users scrolls - Development Ongoing
    * Get the nth div of class content, where n is the contentNumber, and make it shown
    * Set intital divs to be hidden
*/

$(".reveal").addClass("noshow");
var contentNumber = 0;

function reveal() {
    var constraintNumber = contentNumber + 2;
    //IMPORTANT - DO NOT DELETE
    $(window).trigger('resize');
    //IMPORTANT - DO NOT DELETE
    for (i = contentNumber; i < constraintNumber; i++) {
        //Get the nth div of class content, where n is the contentNumber, and make it shown
        $('.reveal').eq(contentNumber).fadeIn('800');
        contentNumber ++;
    }

}

这些部分的样式为 display:none,然后当用户到达窗口底部时,会出现新部分。

我遇到的问题是让我的下拉导航向下滚动到某个部分(例如“滚动到第 6 部分”,即使它是隐藏的)

这是我正在使用的代码的滚动:

$('#nav a').click(function () {
    $('html, body').animate({
        scrollTop: ($(this.hash).offset().top - 17)
    }, 1000,

    function () {});
    return false;
});

我在 FIDDLE 中有这段代码 - http://jsfiddle.net/barrycorrigan/4Ur6R/3/

我只是在寻求一些帮助,让导航与显示部分配合使用。如果您单击导航滚动部分,仍然会显示。

非常感谢任何帮助。

最佳答案

问题是,具有 display:none 的元素不会影响文档高度。您在 .scroll 处理程序中使用它,效果非常好!但是,在您的 .click 处理程序中,您试图获取没有高度的元素的 top 。您需要做的是同时使用 visibility:hiddendisplay:none :

在您的 css 中,

.noshow {
    display:none;
    visibility: hidden;
}

在您的 .click 处理程序中,

    // on click, add the element to the dom before calculating its height
    // it will still be visually hidden, since it has both "display:none;"
    // and "visibility:hidden"
    $(this.hash).show();

    $('html, body').animate({
        scrollTop: ($(this.hash).offset().top - 17)
    }, 1000,

    function () {});

最后,在您的 reveal 函数中,

var $reveal = $('.reveal').eq(contentNumber);                       

// first change visibility to "visible", then fade it in
$('.reveal').eq(contentNumber).css("visibility", "visible").fadeIn("800");

这是一个fiddle我的改变。

关于javascript - 当用户通过导航向下滚动时显示部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087046/

相关文章:

javascript - 以编程方式设置for循环的第三条语句

javascript - 在 AngularJS 中从表单获取数据而不使用双向数据绑定(bind)

javascript - 由于相邻 Sprite ,使用 ATLAS 通过 WebGL 在三 Angular 形上绘制 Sprite 会给出不正确的结果

javascript - 是否可以使用 jQuery.attr() 函数设置多个数据属性?

javascript - 寻找 IE 的开发者插件

javascript - 将 HTML DOM 元素转换为 JavaScript 对象?

javascript - ASP.net 项目图像按钮仅在双击时重定向到另一个页面

jquery - 如何删除 DIV 中除一个元素之外的所有内容?

jquery - 鼠标悬停时显示/隐藏表行中的按钮

javascript - 在 KnovaJs 中,如何允许 Rect 用文本扩展或允许文本具有用文本扩展的边框,就像它在 Html 中的 Div