Show/Hide div with scroll

会有一股神秘感。 提交于 2019-12-04 15:48:20

问题


I know the title isn't the most descriptive and there are many more topics with similar questions like this, but I couldn't find any answers. In fact, I got this far thanks to you guys so, here's what I'm trying to do.

I have a DIV that I want to show when the page is scrolled to a certain position (trigger), marked by #othdiv. This DIV disappears when you scroll further down to the next position (trigger) marked as #othdiv2.

This feels like it's a very simple solution but I just can't figure it out. I have tried conditional if statements, duplicating codes, removing lines, new variables... sigh... please help.

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

Current code sample: http://jsfiddle.net/DnJ2z/124/

Bottom line: I'm trying to do something similar to this: http://mailchimp.com/2012/ (notice the titles [the app, support, operations, etc])


回答1:


Try using && as in: 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();
        }
    });
});

For a much better explanation of logical operators check out: Logical Operators MDN




回答2:


I was playing with your fiddle and manage to get it working. Check if it's what you want:

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


来源:https://stackoverflow.com/questions/16781742/show-hide-div-with-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!