>我有一个网页,在其中插入了"滚动到 id"和"粘滞菜单"jQuery 脚本。我遇到的问题是当我在页面顶部位置时第一次单击菜单。它与顶部的偏移量与其他点击后的偏移量不同(当我不在顶部时)。我写了一个示例代码。如果我不能说出我的意思,我希望你能在样本中找到它。
.HTML:
<header>
<a href="#part1">Part1</a>
<a href="#part2">Part2</a>
<a href="#part3">Part3</a>
<a href="#part4">Part4</a>
<a href="#part5">Part5</a>
<a href="#part6">Part6</a>
</header>
<section id="part1" class="parts"><h1>Part 1</h1></section>
<section id="part2" class="parts silver"><h1>Part 2</h1></section>
<section id="part3" class="parts"><h1>Part 3</h1></section>
<section id="part4" class="parts silver"><h1>Part 4</h1></section>
<section id="part5" class="parts"><h1>Part 5</h1></section>
<section id="part6" class="parts silver"><h1>Part 6</h1></section>
.CSS:
body { margin: 0 0 0 0 }
.parts{ height: 200px; border: 1px gray solid }
.silver { background : silver }
header { background: yellow; height:50px; line-height: 50px; width:100% }
.sticky { position: fixed; left: 0; top: 0; z-index: 2000; width:100% }
h1 { text-align:right }
j查询:
// This section is given from http://stackoverflow.com/questions/5284814/jquery-scroll-to-div
// Scroll to id script
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 50
}, 1000);
return false;
}
}
});
});
// Sticky menu script
var stickyNavTop = $('header').offset().top;
var stickyNav = function(){
var scrollTop = $(window).scrollTop();
if (scrollTop > stickyNavTop) {
$('header').addClass('sticky');
} else {
$('header').removeClass('sticky');
}
};
stickyNav();
$(window).scroll(function() {
stickyNav();
});
js小提琴
请帮我解决这个问题。
替换您的条件
if (scrollTop > stickyNavTop)
跟
if (scrollTop >= stickyNavTop)
以在条件中包含第一部分,并向该零件添加边距顶部。
#part1 {margin-top:50px}