我正在使用此处描述的方法:http://www.wduffy.co.uk/blog/keep-element-in-view-while-scrolling-using-jquery/
最初,我可以使一切正常工作(当前CDN加载jquery)但是当滚动到页面底部时,侧边栏元素继续向下滚动,这使得页面更长,然后再向下滚动创建无限滚动。
我想将侧边栏限制在父元素中 - 在本例中为main-container。当元素到达这个div的底部时,我希望它停止滚动。我试图在这里操纵答案:Jquery Scrolling div - Prevent from entering site footer但收效甚微。有线索吗?
#HTML Structure
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="content-container">
<script>
$().ready(function() {
var $scrollingDiv = $("#sidebar");
$(window).scroll(function(){
var y = $(this).scrollTop(),
maxY = $('#secondary-container').offset().top,
scrollHeight = $scrollingDiv.height(),
offset = 30;
if(y< maxY-scrollHeight-offset ){
$scrollingDiv
.stop()
.animate({"marginTop": ($(window).scrollTop()+offset ) + "px"}, "slow" );
}
});
});
</script>
<h1>header</h1>
<div id="intro-text">
<h3>Sub header</h3>
<p>
Blah blah blah
</p>
</div>
<div id="main-container">
<div id="main">
<!-- Repeat x times -->
<div class="listing">
<p class="listing-description">
Blah
</p>
<p class="listing-response">
Blah
</p>
<br />
<a href="#">Linky</a>
</div>
<!-- End repeat -->
</div>
<div id="sidebar">
<h3>Floaty box content</h3>
Blah
</div>
</div>
<div id="secondary-container">
<div id="secondary-left">
</div>
<div id="secondary-right">
</div>
</div>
<div id="footer">
</div>
</div>
</div>
</body>
</html>
# CSS
#container {
padding:10px;
margin:10px;
margin:auto;
width:1000px;
overflow:auto;
}
.listing {
margin-bottom:5px;
position:relative;
clear:both;
overflow:auto;
width:800px;
}
.listing-description {
float:left;
width: 49%;
font-weight:bold;
}
.listing-response {
float:left;
width:50%;
padding-left:5px;
}
#main-container {
clear:both;
overflow:auto;
}
#main {
float:left;
}
#sidebar {
float:left;
padding-left:10px;
}
#secondary-container {
clear:both;
overflow:auto;
border: 1px solid;
}
#secondary-left {
width:50%;
float:left;
}
#secondary-right {
width:50%;
float:left;
}
答案 0 :(得分:0)
我最终得到了这个:
$(window).scroll(function(){
var y = $(this).scrollTop(),
maxY = ($('#secondary-container').offset().top - $('#sidebar').height() - 110),
scrollHeight = $scrollingDiv.height();
if(y< maxY-scrollHeight){
$scrollingDiv
.stop()
.animate({"marginTop": $(window).scrollTop() + "px"}, "slow" );
}
});
从maxY变量中减去#sidebar hight,加上魔法110数字。我不是百分之百在魔术数字的来源,但在玩了它之后,它符合我的需要。你的旅费可能会改变。