显示在自定义视口上的目标元素,如div或ul

时间:2015-08-25 22:30:22

标签: javascript jquery

我正在使用此插件Viewport Selectors for jQuery,这是源代码:

(function($) {

$.belowthefold = function(element, settings) {
    var fold = $(window).height() + $(window).scrollTop();
    return fold <= $(element).offset().top - settings.threshold;
};

$.abovethetop = function(element, settings) {
    var top = $(window).scrollTop();
    return top >= $(element).offset().top + $(element).height() - settings.threshold;
};

$.rightofscreen = function(element, settings) {
    var fold = $(window).width() + $(window).scrollLeft();
    return fold <= $(element).offset().left - settings.threshold;
};

$.leftofscreen = function(element, settings) {
    var left = $(window).scrollLeft();
    return left >= $(element).offset().left + $(element).width() - settings.threshold;
};

$.inviewport = function(element, settings) {
    return !$.rightofscreen(element, settings) && !$.leftofscreen(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
};

$.extend($.expr[':'], {
    "below-the-fold": function(a, i, m) {
        return $.belowthefold(a, {threshold : 0});
    },
    "above-the-top": function(a, i, m) {
        return $.abovethetop(a, {threshold : 0});
    },
    "left-of-screen": function(a, i, m) {
        return $.leftofscreen(a, {threshold : 0});
    },
    "right-of-screen": function(a, i, m) {
        return $.rightofscreen(a, {threshold : 0});
    },
    "in-viewport": function(a, i, m) {
        return $.inviewport(a, {threshold : 0});
    }
});


})(jQuery);

我想在可滚动的div上使用此插件,或者不在窗口上使用此插件。

如果我将选择器$(window)改为其他任何东西,那么一切都很完美。

如何使其自定义,例如:

$('ul li').inVeiwPort({viewPort:$('ul')}).css('background-color','red');

1 个答案:

答案 0 :(得分:0)

这部分:

$.extend($.expr[':'].....

创建自定义伪选择器,以便执行以下操作:

$('ul li:in-viewport').css('background-color','red');

或者更好

$('ul:in-viewport li:in-viewport').css('background-color','red');

我从未使用过此插件,因此请使用各种变体来查看最适合您的内容