$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on("resize scroll", function() {
    $(".color").each(function() {
        var activeColor = $(this).attr("id");
        if ($(this).isInViewport()) {
            // do someting
        } else {
            // do someting
        }
    });
});

延伸思考:

下面的代码是判断向下滚动进入到了屏幕的1/3处或者向上滚动进入屏幕的1/3处均可触发,判断条件可写成:

$.fn.isinViewport30percent = function() {
	var $sensitive = $(window).height() * 0.3;
	var elementTop = $(this).offset().top + $sensitive;	
	var elementBottom = elementTop + $(this).outerHeight() - $sensitive * 2;
	var viewportTop = $(window).scrollTop();
	var viewportBottom = viewportTop + $(window).height();
	return elementBottom > viewportTop && elementTop < viewportBottom;
};

下面的代码是,还未进入屏幕范围内。离屏幕还差500px时就触发,判断条件可写成:

 $.fn.isNearViewport = function() {
    var $sensitive = 500;
    var elementTop = $(this).offset().top - $sensitive;
    if (elementTop < 0) {
        elementTop = 0;
    }
    var elementBottom = elementTop + $(this).outerHeight() + $sensitive * 2;
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
}; 
本篇文章相关标签: