我在http://communitychessclub.com/index.php使用 position:fixed 菜单来保持菜单在屏幕上,即使用户滚动:
CSS:
#sticky {margin:0 auto; display:table}
#sticky.stick {position: fixed; top: 0; margin-left:48px; z-index: 10000; }
JS:
<script>
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top)
$('#sticky').addClass('stick')
else
$('#sticky').removeClass('stick');
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
$(window).scroll((function() {
var a='', // a buffer to the hash
w = $(window);
return function() {
var h = location.hash;
// if hash is different from the previous one, which indicates
// the hash changed by user, then scroll the window down
// update the buffer
if (h != a) {
a = h;
w.scrollTop(w.scrollTop()-150)
}
};
})());
</script>
但是人们抱怨链接到同一页面上的 ID 会导致屏幕突然滚动。所以我在http://www.spydertrap.com/blog/2012/08/user-experience-jquery-smooth-page-anchor-transitions/找到了“使用 jQuery Smooth Page Anchor Transitions 改善用户体验”,并且喜欢这个演示。非常喜欢它,以至于我想将下面的 jquery 代码与上面的 jquery 代码混合在一起,以实现平滑的 jquery 滚动。
他们使用这个(但这里存在其他版本......问题是如何加入两者)
jQuery代码:
function goToByScroll(id){
$('html,body').animate({scrollTop: $(id).offset().top},'slow');
}
HTML:
<ul class="nav">
<li><a href="#chapter1">Chapter 1</a></li>
<li><a href="#chapter2">Chapter 2</a></li>
<li><a href="#chapter3">Chapter 3</a></li>
</ul>
JS 启动器:
$(document).ready(function(){
$('.nav a').click(function(){
goToByScroll($(this).attr('href'));
return false;
});
});
这可以与上面的 jquery 代码结合吗?