我的页面左侧有一个固定的div(#navigation),右边有一个可滚动的div(#content)。当单击#navigation中的链接时,它应该触发平滑滚动到#content的更正部分。在链接上第二次单击后,它会转到#content的错误部分。您可以在http://germanespitia.com
中查看所有实际的源代码所以..
<div id="navigation">
`enter code here` <div class="nav-item" data-page="about-me">
<a href="#about-me" >
</a>
</div>
<div class="nav-item" data-page="projects">
<a href="#projects" >
</a>
</div>
<div class="nav-item" data-page="portfolio">
<a href="#portfolio" >
</a>
</div>
<div class="nav-item" data-page="contact">
<a href="#contact" >
</a>
</div>
</div>
<div id="content">
<div class="section" id="about-me">
</div>
<div class="section" id="projects">
</div>
</div>
$('#navigation a').click(function() {
var goTo = $($(this).attr('href')); // selects element that was clicked
var offset = goTo.offset(); //grabs position of element
$('#content').animate({
scrollTop: goTo.offset().top
}, 1000);
return false;
$('#about-me h1').text(goTo.attr('href'));
});
答案 0 :(得分:0)
$('#navigation a').click(function() {
var goTo = $($(this).attr('href')); // selects element that was clicked
var offset = goTo.offset(); //grabs position of element
$('#content').animate({
scrollTop: goTo.offset().top
}, 1000);
return false;
$('#about-me h1').text(goTo.attr('href'));
});
您滚动的偏移量是您应该修复的元素中当前位置的偏移量
scrollTop: goTo.offset().top
要
scrollTop: $('#content')[0].scrollTop + goTo.offset().top
可能有效
答案 1 :(得分:0)
只有当偏移非常大时滚动才能正常工作,它会在传递给animate
函数的1000毫秒内更快地完成。一个想法是根据当前偏移的差异和我们想要达到的差异来计算完成动画所需的时间。像这样:
$('#navigation a').on("click", function () {
var gt = $($(this).attr('href')),
ofs = gt.offset(),
tp = ofs.top,
crOff = $('#content').scrollTop(),
anim = Math.abs(crOff - tp) * 100; //ESTIMATE TIME TO ANIMATE
if (x > 3000) x = 3000;//IF GAP IS TOO LARGE, IT IS PAINFULLY SLOW
$('#content').stop().animate({
scrollTop: tp
}, anim); //USE anim VARIABLE TO CONTROL ANIMATION TIME
event.preventDefault();
event.stopPropagation();
});
看看这个小提琴:http://jsfiddle.net/Vqce7/