Довольно плохо знакомы с jQuery и JavaScript в целом.Я смоделировал пример моей проблемы на http://jsbin.com/alibi3/2/ - с объяснением ниже.
У меня есть div, который после того, как пользователь прокручивает определенную точку на странице, назначаетсякласс «исправлено», поэтому он следует за пользователем вниз по странице.Это прекрасно работает само по себе.
Проблема в том, что содержимое выше этого div можно переключать, чтобы показывать / скрывать - и когда он отображается, фиксированный класс все еще применяется в той точке, в которой он был бы, если быон был скрыт, поэтому кажется, что он «прыгает».
Как мне сказать моей функции добавления фиксированных классов, что div был показан / скрыт, и настроить точку, в которой «фиксированный»класс добавлен?
Спасибо.
HTML:
<div id="drawer">
<a href="#">Click here to toggle drawer</a>
<p id="drawercontents">Here is the stuff in the drawer; hidden by default.</p>
</div>
<div id="article">
blah, blah...
</div>
<div id="nav">
This should follow down the page once we scroll past the start of the article,
and 'stick' back in place when we are back at the top.
</div>
CSS:
#article {
width: 400px;
float: left;
margin-right: 20px;
padding: 20px;
background: #eee;
}
#nav {
width: 200px;
float: left;
background: #ff0;
padding: 20px;
}
#drawer {
width: 660px;
padding: 20px;
color:#fff;
background: #000;
margin-bottom: 10px;
}
.fixed { position: fixed; left: 460px; top: 0px; }
JavaScript:
$(document).ready(function() {
$('#drawercontents').hide();
$('#drawer a').click(function(e){
e.preventDefault();
$('#drawercontents').toggle('fast');
});
var top =$('#nav').offset().top - parseFloat($('#nav').css('marginTop').replace(/auto/, 0));
$(window).scroll(function () {
// what is the y position of the scroll?
var y = $(window).scrollTop();
// whether that's below the start of article?
if (y >= top) {
// if so, add the fixed class
$('#nav').addClass('fixed');
} else {
// otherwise, remove it
$('#nav').removeClass('fixed');
}
});
});