我正在创建我的第一个单页网站,但它运行不正常。这是我目前拥有的:http://jsfiddle.net/wfjgq7xq/
首先,当我单击一个链接时,即测试 3,测试 2 突出显示它在那个页面上,然后我必须稍微滚动页面以突出显示测试 3。
其次,对高亮显示有延迟 react ,当滚动页面时,高亮显示应该在滚动浏览的每个页面时发生变化,这是延迟的,到那时它不会改变几秒钟我' m 在页面底部。
第三,页面的开始总是在标题下面,我需要将它向下移动但是 top:60;没用
这是我的 jQuery:
jQuery(document).ready(function($) {
$('.scroll').click(function(){
var $target = $($(this).attr('href'));
$(this).parent().siblings().removeClass('active');
$(this).parent().addClass('active');
$('body').stop().scrollTo( $target , 800, {'axis':'y'});
return false;
});
$(window).on('scroll', function(){
var scrollPosition = $(window).scrollTop();
$('div[id^="test"]').each(function(i){
if($(this).position().top < scrollPosition) {
$('nav li').removeClass('active');
$('nav li:eq('+i+')').addClass('active');
}
});
});
});
更新:延迟似乎是 Safari 的问题!
最佳答案
您需要包括标题的偏移量。滚动不考虑标题的位置,因为它固定在那里。
var offsetHeader = 60;
$('.scroll').click(function(){
var $target = $($(this).attr('href'));
$(this).parent().siblings().removeClass('active');
$(this).parent().addClass('active');
$('body').stop().scrollTo( $target , 800, {'axis':'y', offset: -offsetHeader});
return false;
});
$(window).on('scroll', function(){
var scrollPosition = $(window).scrollTop();
$('div[id^="test"]').each(function(i){
console.log(1, $(this).position().top);
console.log(2, scrollPosition);
if($(this).position().top <= scrollPosition + offsetHeader) {
$('nav li').removeClass('active');
$('nav li:eq('+i+')').addClass('active');
}
});
});
基本上,您可以告诉 jquery scrollto 插件偏移滚动。同样对于导航链接,您还需要在进行比较时包括偏移量。
要在页面开头添加距页眉的偏移量,您可以添加一个具有高度的不可见容器:
在 CSS 中添加:
div#offsetBlock
{
height: 60px;
display: block;
}
在 HTML 中,将其添加到标题之后和第一个容器 test1 之前
<div id="offsetBlock">
</div>
注意:您可能无法正确滚动直到 test6,因为滚动已经到达页面末尾。
关于jquery - 一页网站的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25240011/