【问题标题】:Show/Hide div with scroll使用滚动显示/隐藏 div
【发布时间】:2013-05-27 23:19:21
【问题描述】:

我知道标题不是最具有描述性的,还有更多类似问题的主题,但我找不到任何答案。事实上,多亏了你们,我才走到这一步,这就是我正在努力做的事情。

我有一个 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/(注意标题[应用程序、支持、操作等])

【问题讨论】:

  • 你们太棒了!现在,如果我可以滥用您的好意:我将如何向 topOfthDiv 添加“缓冲区”。意思是,现在当滚动触摸 div 时,div 隐藏/显示。我怎样才能做到这一点,以便它仅在滚动过去 div 后 200px 之后才切换。这有意义吗?
  • 啊哈,我在 othdiv 中添加了 position:relative;top:200px;,问题解决了。谢谢!

标签: jquery css scroll show-hide


【解决方案1】:

尝试使用&amp;&amp;,如:if (this and that){do something} else{don't}

Working Example

$(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();
        }
    });
});

要更好地解释逻辑运算符,请查看:Logical Operators MDN

【讨论】:

    【解决方案2】:

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

    $(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            
            }           
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 2014-05-26
      • 2017-11-16
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多