我的one DIV
页面上有一个html结构,里面包含two other DIVS
,其中第一个是较小的header
,另一个是navigation
栏( #main-template-navigation
)。这两个div都是静态的,因此滚动页面时它们不会跟随。我现在要做的是让导航div跟随滚动页面。我正在使用下面的代码这样做,但是当位置变为固定时,网站会跳起来,这不是那么顺利。
所以我的问题是如何让它'顺畅'?我一直在尝试使用clone();
函数,但只要我没有单独的div将其附加到我想要避免的内容,它就不起作用。
$(function() {
var stickyHeaderTop = $('#main-template-navigation').offset().top;
$(window).scroll(function() {
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#main-template-navigation').css({position: 'fixed', top: '0px'});
} else {
$('#main-template-navigation').css({position: 'static', top: '0px'});
}
});
});
答案 0 :(得分:2)
以下是解决问题的一种方法: 添加固定时,在顶部添加“缓冲”div,删除时将其删除。缓冲区div高度与导航高度
匹配DEMO:https://jsfiddle.net/4vbzvxd7/5/
$(function() {
var stickyHeaderTop = $('#main-template-navigation').offset().top;
$(window).scroll(function() {
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#main-template-navigation').css({position: 'fixed', top: '0px'});
if(!$('#main-template-navigation-container').length){
$('<div/>',{
id: 'main-template-navigation-container',
css: {
height: $('#main-template-navigation').height()
}
}).prependTo('body');
}
} else {
$('#main-template-navigation').css({position: 'static', top: '0px'});
$('#main-template-navigation-container').remove();
}
});
});
答案 1 :(得分:0)
我会将div设置为始终固定并定义高度大小,如果我想开始任何效果,我会做的唯一更改。
header{
position: fixed;
width: 100%;
height: 108px;
// set animation
-webkit-transition: all 0.4s ease;
transition: all 0.4s ease;
}
点击此处了解更多信息: