html、js、css 示例为https://jsfiddle.net/t9mfmaa3/5/ .
/* Latest compiled and minified JavaScript included as External Resource */
$(function() {
var $sidebar = $("#e"),
$window = $(window),
$offset = $sidebar.offset(),
$topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > $offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - $offset.top + $topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 0
});
}
});
});
/* Latest compiled and minified CSS included as External Resource*/
/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
margin: 10px;
}
#c {
background-color: red;
height: 2400px
}
#e {
background-color: lightblue;
height: 600px
}
#b {
height: 2400px;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="a">
<div id="b" class="column col-xs-3 col-sm-3">
<div id="e" class="">
blue
</div>
</div>
<div id="c" class="center_column col-xs-9 col-sm-9">
red
</div>
</div>
</div>
</div>
我试图让蓝色 block 不超过黄色 block ,这意味着蓝色 block 始终位于黄色 block 中。我的想法是设置代码来检测黄色 block 和蓝色 block 。但我没有成功。有人有什么建议吗?谢谢
最佳答案
如果你已经在使用 bootstrap,你也可以使用他们的后缀 javascript。
这是一个例子:
$(function() {
var $sidebar = $("#e"),
$body = $('body'),
$parent = $('#b'),
topPadding = 15,
offset=$sidebar.offset();
$sidebar.affix({
offset: {
top: function() {
return $parent.offset().top - topPadding;
},
bottom: function() {
return $(document.body).height() - ($parent.offset().top + $parent.outerHeight());
}
}
});
});
您可能会注意到它在接近尾声时表现得有点奇怪和跳跃,但是当在真实网站上(而不是在 iframe 内)使用它时,这种情况应该会消失
关于javascript - 如何设置js函数滚动让它不超过父级的底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517695/