Jquery code works, but there must be a way to slim it down

ぐ巨炮叔叔 提交于 2019-12-11 07:05:19

问题


I've managed to finally get this code working, which fades divs in and out based on the hashtag in the URL and whether the divs touch the top or bottom of the window. The jQuery looks like this:

var distanceFromTop = $(window).scrollTop(),
    distanceFromBottom = $(window).scrollTop() + $(window).height();

var divOneFromTop = $("#div-one").offset().top,
    divOneFromBottom = divOneFromTop + $("#div-one").height();

if (window.location.hash == "#div-one" && distanceFromTop >= divOneFromTop && !(distanceFromBottom > divOneFromBottom)) {
    $(".div-one-info").fadeIn(300);
} else {
    $(".div-one-info").fadeOut(300);
}

var divTwoFromTop = $("#div-two").offset().top,
    divTwoFromBottom = divTwoFromTop + $("#div-two").height();

if (window.location.hash == "#div-two" && distanceFromTop >= divTwoFromTop && !(distanceFromBottom > divTwoFromBottom)) {
    $(".div-two-info").fadeIn(300);
} else {
    $(".div-two-info").fadeOut(300);
}

The thing is that I need around eight more divs and I'm repeating myself a ridiculous amount of time. Does anybody have an idea about how I could slim this down and make ita little more "automated", so I don't have to write, #div-one and divOne etc. all the time?


回答1:


Something like the following:

var id = window.location.hash;

var divFromTop = $(id).offset().top,
    divFromBottom = divFromTop + $(id).height();

if (distanceFromTop >= divFromTop && !(distanceFromBottom > divFromBottom)) {
    $(id.replace("#", ".") + "-info").fadeIn(300);
} else {
    $(id.replace("#", ".") + "-info").fadeOut(300);
}

You could probably make this a little more readable but the basic idea is that you use the document location hash to identify the necessary elements.




回答2:


You can use attribute starts with selector to iterate through your div, get the id and compare with the location hash:

$.each($('[id^="div-"]'), function () {
    var id = $(this).attr('id'),
        divOneFromTop = $(this).offset().top,
        divOneFromBottom = divOneFromTop + $(this).height();

    if (window.location.hash == "#" + id && distanceFromTop >= divOneFromTop && !(distanceFromBottom > divOneFromBottom)) {
        $("." + id + "-info").fadeIn(300);
    } else {
        $("." + id + "-info").fadeOut(300);
    }
});


来源:https://stackoverflow.com/questions/21885540/jquery-code-works-but-there-must-be-a-way-to-slim-it-down

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