jQuery 当用户到达页面底部时如何显示 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2768264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show div when user reach bottom of the page?
提问by Kenan
When user scrolls to the bottom of the page I want to show some div, with jQuery of course. And if user scrolls back to he top, div fade out. So how to calculate viewport (or whatever is the right name) :)
当用户滚动到页面底部时,我想显示一些 div,当然是使用 jQuery。如果用户滚动回顶部,div 淡出。那么如何计算视口(或任何正确的名称):)
Thanks
谢谢
回答by BalusC
This must get you started:
这必须让你开始:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2768264</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(window).scroll(function() {
if ($('body').height() <= ($(window).height() + $(window).scrollTop())) {
alert('Bottom reached!');
}
});
});
</script>
<style>
body { margin: 0; }
</style>
</head>
<body>
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
</body>
</html>
This assumes that body
has a margin
of 0
. Else you'll need to add the top and bottom margin to the $('body').height()
.
这假定body
有一个margin
的0
。否则,您需要将顶部和底部边距添加到$('body').height()
.
回答by David Passmore
You can use the following:
您可以使用以下内容:
$(window).scroll(function() {
if ($(document).height() <= ($(window).height() + $(window).scrollTop())) {
//Bottom Reached
}
});
I use this because i have
我使用这个是因为我有
body {
height:100%;
}
Hope this helps
希望这可以帮助
回答by Hossam Mourad
Here's a small edit on the BalusC's code if you want to show a div not a javascript popup:
如果你想显示一个 div 而不是 javascript 弹出窗口,这里是对 BalusC 代码的一个小编辑:
<head>
<title>SO question 2768264</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(window).scroll(function() {
if ($("body").height() <= ($(window).height() + $(window).scrollTop())) {
$("#hi").css("display","block");
}else {
$("#hi").css("display","none");
}
});
});
</script>
<style>
body { margin: 0; }
#hi {
background: red; color: #FFF; position: fixed; bottom: 0px; right: 0px; display: none;
}
</style>
</head>
<body>
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p<p>p
<div id="hi">HIIIIIIIIIIII</div>
</body>