用滚动显示/隐藏div

我知道标题不是最具描述性的,并且还有更多类似问题的主题,但我找不到任何答案。 事实上,我得到了这么多,谢谢你们,所以,这就是我要做的。

当页面滚动到某个位置(触发器)时,我想要显示一个DIV,由#othdiv标记。 当您进一步向下滚动到标记为#othdiv2的下一个位置(触发器)时,此DIV会消失。

这感觉就像是一个非常简单的解决方案,但我无法弄明白。 我已经尝试过条件if语句,复制代码,删除行,新变量……叹息……请帮忙。

$(document).ready(function() { $("#dvid").hide(); //hide your div initially var topOfOthDiv = $("#othdiv").offset().top; var topOfOthDiv2 = $("#othdiv2").offset().top; $(window).scroll(function() { if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div? $("#dvid").show(); //reached the desired point -- show div } else if($(window).scrollTop() < topOfOthDiv) { //scrolled past the other div? $("#dvid").hide(); //reached the desired point -- show div } }); }); 

当前代码示例: http : //jsfiddle.net/DnJ2z/124/

一句话:我正在尝试做类似的事情: http : //mailchimp.com/2012/ (注意标题[应用程序,支持,操作等])

尝试使用&&如下:if(this and that){do something} else {do not}

工作实例

 $(document).ready(function () { var topOfOthDiv = $("#othdiv").offset().top; var topOfOthDiv2 = $("#othdiv2").offset().top; $(window).scroll(function () { if ($(window).scrollTop() > topOfOthDiv && $(window).scrollTop() < topOfOthDiv2) { $("#dvid").show(); } else { $("#dvid").hide(); } }); }); 

有关逻辑运算符的更好解释,请查看: 逻辑运算符MDN

我正在玩你的小提琴,并设法让它工作。 检查它是否是你想要的:

 $(document).ready(function() { $("#dvid").hide(); //hide your div initially var topOfOthDiv = $("#othdiv").offset().top; var topOfOthDiv2 = $("#othdiv2").offset().top; $(window).scroll(function() { if($(window).scrollTop() > topOfOthDiv && $(window).scrollTop() < topOfOthDiv2) { //scrolled past the other div? $("#dvid").show(); //reached the desired point -- show div } else if($(window).scrollTop() < topOfOthDiv || $(window).scrollTop() > topOfOthDiv2) { //scrolled past the other div? $("#dvid").hide(); //reached the desired point -- show div } }); });