我有一个页面,其中包含许多部分,当用户滚动页面时会显示这些部分。这是完整的工作代码。
/**
* 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:hidden
和 display: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/