jQuery代码有效,但是必须有一种方法可以简化它 [英] Jquery code works, but there must be a way to slim it down

查看:86
本文介绍了jQuery代码有效,但是必须有一种方法可以简化它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于设法使此代码起作用,该代码根据URL中的井号标签以及div接触窗口的顶部还是底部,使div淡入和淡出. jQuery如下所示:

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

问题是,我需要再增加大约8个div,而我要重复自己的时间很可笑.有人知道我如何精简一下并使ita更加自动化",所以我不必一直写#div-one和divOne等吗?

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?

推荐答案

类似以下内容:

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.

这篇关于jQuery代码有效,但是必须有一种方法可以简化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆