javascript 上下滚动时显示和隐藏 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18088461/
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
Show and hide a Div on scroll up and down
提问by Pat
I'm trying to make my simple "scroll back to the top" image appear and disappear based on how far away from the top of the page you are. For the sake of example, let's say 100 pixels away from the top.
我正在尝试根据您离页面顶部的距离来显示和消失我的简单“滚动回顶部”图像。例如,假设距顶部 100 像素。
Here's what I have. It seems to work on scroll down, the image div fades in.
这就是我所拥有的。它似乎可以向下滚动,图像 div 淡入。
When I scroll back to the top, the div doesn't fadeOut
. Any tips?
当我滚动回顶部时,div 没有fadeOut
。有小费吗?
$(window).scroll(function() {
if ($(this).scrollTop()>100)
{
$('#toTop').fadeIn();
}
else
{
$('.#toTop').fadeOut();
}
});
回答by yckart
I think you've a typo in your code: $('.#toTop').fadeOut();
should be $('#toTop').fadeOut();
我认为你的代码中有一个错字:$('.#toTop').fadeOut();
应该是$('#toTop').fadeOut();
Update
更新
Just a simple improvement. To prevent the element be fadedall the time you scroll, check if it was already faded earlier:
只是一个简单的改进。为了防止元件褪去所有你滚动的时间,检查它是否已经褪去更早:
var $toTop = $('#toTop');
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$toTop.fadeIn();
} else if ($toTop.is(':visible')) {
$toTop.fadeOut();
}
});