功能上的平滑滚动+偏移goToNext
我想从顶部添加一个偏移量,并平滑滚动到以下功能, 功能位于一个固定的按钮上,并沿着页面跟随用户。此按钮必须能够滚动浏览多个锚点,然后返回第一个锚点,理想的偏移距离顶部为105像素。拖网几小时寻求帮助,并没有jquery知道如何解决这个问题,任何帮助?这里 类似的例子 - http://www.google.com/nexus/7/(按钮,右下)功能上的平滑滚动+偏移goToNext
<script>
var max = 6;
function goToNext() {
var hash = String(document.location.hash);
if (hash && hash.indexOf(/anchor/)) {
var newh = Number(hash.replace("#anchor",""));
(newh > max-1) ? newh = 0 : void(null);
document.location.hash = "#anchor" + String(newh+1);
} else {
document.location.hash = "#anchor1";
}
}
</script>
<a href="#" onclick="goToNext();return false;"></a>
<div id="anchor1"></div>
<div id="anchor2"></div>
<div id="anchor3"></div>
<div id="anchor4"></div>
<div id="anchor5"></div>
<div id="anchor6"></div>
你可以把它滚动顺利使用animate({scrollTop:value},delay)
的元素。
$('document').ready(function() {
//on DOM ready change location.hash to 'anchor1'
window.location.hash = 'anchor1';
//GO TO NEXT click event:
$('a').click(function (e) {
//preventing the default <a> click (href="#")
e.preventDefault();
//get the current hash to determine the current <div> id
var hash = window.location.hash,
//find the (next) immediate following sibling of the current <div>
$next = $(hash).next('div');
//check if this next <div> sibling exist
if ($next.length) {
var id = $next.attr('id'),
nextOffsetTop = $next.offset().top;
//animate scrolling and set the new hash
$('body, html').animate({scrollTop: nextOffsetTop}, 'slow');
window.location.hash = id;
}else{
//else if the next <div> sibling does not exist move to the first anchor
var first = '#anchor1';
$('body, html').animate({scrollTop: $(first).offset().top},'slow');
window.location.hash = first;
}
});
})
看到这个jsfiddle。
然后是闪烁。其实它不是闪烁,但有点生涩,如果你仔细观察上面的代码。我先设置animate(scrollTop)
,然后更改散列window.location.hash = id
。现在,当动画开始滚动时,突然我们正在更改散列,它往往直接跳到下一个<div>
(这是默认的haschange
事件),但被animate()
拉回,导致滚动为生涩。
我们不能停止haschange
事件的默认传播,可能有解决方案,但不能保证它可以在所有浏览器上运行,但每个浏览器在haschange
事件时都有不同的行为。但是感谢@Andy E提供的SO帖子解决方案,我们不需要停止haschange传播。我们可以只是简单地改变哈希值,重新设置为最后的scrollTop()
位置,然后根据需要动画滚动!
//get the current scrollTop value
var st = $(window).scrollTop();
//change the hash
window.location.hash = id;
//reset the scrollTop
$(window).scrollTop(st);
//animate scrolling
$('body, html').animate({scrollTop: nextOffsetTop}, 'slow');
检查此更新jsfiddle。
现在让我们来谈谈HTML5 History API。我之所以没有首先介绍这一点,是因为它在HTML5(特别是IE)浏览器中的实现方式不同,并且没有对HTML4浏览器的回退,使得此方法在某种程度上不一致。但是,我可以使用插件来正确完成此操作。
这里是如何使用history.pushState()
做到这一点:
if ($next.length) {
var id = $next.attr('id'),
nextOffsetTop = $next.offset().top;
history.pushState({state:id}, id, '#'+id);
$('body, html').animate({scrollTop: nextOffsetTop - 105}, 'slow');
}
看到这个jsfiddle。
就是这样。干杯!
我希望在一个按钮上的功能固定,并沿着页面的用户。此按钮必须能够滚动浏览多个锚点,然后返回第一个锚点,理想的偏移距离顶部为105像素。 有没有办法修改所提供的代码(谢谢!它解决了滚动问题),在最后一个锚点被击中后滚动回顶部? 谢谢你的回答:) – webbist
$('body,html')。animate({scrollTop:nextOffsetTop - 105},'slow'); 所以通过编辑这个我有我的抵消和我的平滑滚动,但如何让它从顶部重复,一旦你到达最后一个锚? – webbist
我看到你想要元素抵消前的顶部间距105。我更新了这个[** jsfiddle **](http://jsfiddle.net/LR9Cd/8/)。 –