$(window).scroll(function(){
$("#theFixed").css("bottom",Math.max(0,250-$(this).scrollTop()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<div id="theFixed" style="position:fixed;top:250px;background-color:red">SOMETHING</div>
STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>STUFF <BR>
...几乎可以正常工作,但theFixed
的高度会在滚动时发生变化,如何解决?
编辑:也许我不清楚,我不需要在'窗口'或外部容器的底部修复内容,我可以使用CSS。
答案 0 :(得分:1)
您可以使用CSS height
属性显式设置所需的高度:
$(window).scroll(function() {
$("#theFixed").css("bottom", Math.max(0, 250 - $(this).scrollTop()));
});
#theFixed {
height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<div id="theFixed" style="position:fixed;top:250px;background-color:red">SOMETHING</div>
STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>STUFF
<BR>
此外,与您的问题无关,但作为一般建议:当您为scroll
,resize
等事件注册事件监听器时,您通常还需要 debounce 事件处理程序执行,以便UI保持对其他类型事件的响应。
有关event debouncing的更多信息。