我遇到的问题应该是一件简单的问题。我有一个特定的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;
}
答案 0 :(得分:0)
我已将其设为简单并将其上传到codepen中。这将解决您的问题。我也对CSS做了一些小改动,但你可以忽略它们并专注于它的jquery部分。
codepen:https://codepen.io/vikrant-icd/pen/GEQdxZ
jQuery的:
$(window).scroll(function() {
var elTop = $("wrapper").position(),
window = $("body").scrollTop(),
wrapTop = elTop.top - 80;
if (window >= wrapTop) {
$("#chapters").addClass("sticky");
console.log("sticky");
} else {
$("#chapters").removeClass("sticky");
}
});
答案 1 :(得分:0)
我最终要做的是将代码放在我的索引页面上 - 这不是理想的情况。但代码看起来像这样:
$(function () {
$(window).scroll(function () {
if ($(window).width() > 768) {
if ($(this).scrollTop() > 1150) {
$('#chapters').addClass('sticky');
} else {
$('#chapters').removeClass('sticky');
}
}
});
});