【发布时间】:2017-06-28 20:16:41
【问题描述】:
我在处理一件应该很简单的事情时遇到了麻烦。我有一个特定的 div,当它滚动到某个点时,我想让它变粘(固定)。但它不起作用。我让它变粘的条件似乎从未得到满足。事实上,无论我滚动多少,我正在跟踪的偏移量似乎都没有改变。谁能给点建议?
html:
<navbar>
<a href="http://www.post-gazette.com/"><pglogo> </pglogo></a>
<textbranding>title</textbranding>
<social>
<a class="fa fa-facebook" target="_blank" href=""></a>
<a class="fa fa-twitter" target="_blank" href=""></a>
</social>
</navbar>
<section class="module parallax parallax-1">
<h2>Title</h2>
<h3>teaser</h3>
</section>
<wrapper>
<div id="chapters" style="text-align: center;">
<div class="linkChapter">main story</div> <div class="linkChapter">chapter 2</div> <div class="linkChapter">chapter 3</div><div class="linkChapter">chapter 4</div> <div class="linkChapter">chapter 5</div>
</div>
<section id="story-start" class="row medium-9 large-7 columns storyMain">
(lots of text)
</section>
</wrapper>
jquery:
var $window = $(window),
$stickyEl = $('wrapper'),
elTop = $stickyEl.offset().top;
offset = elTop - $( document ).scrollTop();
//elTop - $(window).scrollTop()
console.log(elTop);
$window.scroll(function() {
console.log(elTop-$(window).offset().top);
if (elTop <= 40) {
$('#chapters').addClass('sticky');
} else {
$('#chapters').removeClass('sticky');
}
//$stickyEl.toggleClass('sticky', elTop <= 40);
});
css
navbar {
width: 100vw;
height: 50px;
background: linear-gradient(rgb(0, 0, 0),rgba(0, 0, 0, 0.75));
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
align-content: center;
align-items: center;
padding: 0 10px;
position: fixed;
z-index: 3000;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.6);
}
wrapper {
transition: background 2.0s ease;
display: block;
position: relative;
}
wrapper p {
transition: all 2.0s ease;
}
section.module.parallax {
height: 1200px;
background-position: 50% 50%;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
section.module.parallax-1 {
background-image: url("../img/main/myimage.jpg");
position: relative;
}
#chapters {
margin-bottom: 30px;
position: absolute;
width: 100%;
top: -30px;
}
#chapters.sticky {
position: fixed;
top: 50px;
}
.linkChapter {
cursor: pointer;
background-color: black;
color:white;
padding: 3px 7px;
display:inline-block;
}
.linkChapter:hover {
opacity: .7;
}
【问题讨论】: