我正在尝试让我的内容在接近页面两端时淡入。当触发器设置在最顶部和最底部时,淡入淡出效果很好,但当我设置距离 (200px) 时,淡入淡出不再起作用,内容只出现。
$(window).scroll(function(){
if($(window).scrollTop()<=200){
$('#about .content').stop(true,true).fadeIn("5s");
}
else {
$('#about .content').stop(true,true).fadeOut("10s");
}
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
$('#work .content').stop(true,true).fadeIn("5s");
} else {
$('#work .content').stop(true,true).fadeOut("5s");
}
});
最佳答案
发生的事情是你有两个相互对抗的函数:
第一个函数有一个“if-else”语句,第二个函数也有。 这意味着每次滚动时每个函数都会做一些事情。 有多种方法可以解决这个问题。
我要解决的方法是使用变量并更新约束。
假设我们有一个变量 onScreen,如果段落在屏幕上则值为 1,否则值为 0:
例如:
<div style="height: 800px">Example of scroll with fadeIn, fadeOut.
<p style="margin-top:300px;">These paragraphs will go away when you have scrolled
more than 10 pixels from the top. They will appear again when you have scrolled
to a proximity of 50 pixels from the bottom. They will also appear if you go
within a proximity of 10 pixels of the top again.</p>
</div>
现在是 jQuery 代码:
var $onScreen = 1;
$(window).scroll(function(){
if($(window).scrollTop() < 10){
if ($onScreen == 0)
{
$("p:first").stop(true,true).fadeIn("slow", "linear");
$onScreen = 1;
}
}
if($(window).scrollTop() <= 20 && $(window).scrollTop() >= 10){
if ($onScreen == 1)
{
$("p:first").stop(true,true).fadeOut("slow", "linear");
$onScreen = 0;
}
}
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) {
if ($onScreen == 0)
{
$("p:first").stop(true,true).fadeIn("slow", "linear");
$onScreen = 1;
}
}
});
现在这不是最简洁的方法,我也不是故意的:通过使代码更广泛一些,我希望你能理解为什么它现在有效而以前无效(这样你实际上从中学习)。
我在 Fiddle 上为您准备了一个实例:http://jsfiddle.net/ycCAb/4/
我希望这能回答您的问题。祝你好运!
关于javascript - 滚动的淡入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16844133/