Change text color based on brightness of the covered background area?

前端 未结 8 1586
悲哀的现实
悲哀的现实 2020-11-27 09:53

I\'ve thought about the following for a while already, so now I want to know your opinions, possible solutions, and so on.

I am looking for a plugin or technique tha

8条回答
  •  醉梦人生
    2020-11-27 10:21

    Here's my attempt:

    (function ($) {
        $.fn.contrastingText = function () {
            var el = this,
                transparent;
            transparent = function (c) {
                var m = c.match(/[0-9]+/g);
                if (m !== null) {
                    return !!m[3];
                }
                else return false;
            };
            while (transparent(el.css('background-color'))) {
                el = el.parent();
            }
            var parts = el.css('background-color').match(/[0-9]+/g);
            this.lightBackground = !!Math.round(
                (
                    parseInt(parts[0], 10) + // red
                    parseInt(parts[1], 10) + // green
                    parseInt(parts[2], 10) // blue
                ) / 765 // 255 * 3, so that we avg, then normalize to 1
            );
            if (this.lightBackground) {
                this.css('color', 'black');
            } else {
                this.css('color', 'white');
            }
            return this;
        };
    }(jQuery));
    

    Then to use it:

    var t = $('#my-el');
    t.contrastingText();
    

    This will straight away, make the text either black or white as appropriate. To do the icons:

    if (t.lightBackground) {
        iconSuffix = 'black';
    } else {
        iconSuffix = 'white';
    }
    

    Then each icon could look like 'save' + iconSuffix + '.jpg'.

    Note that this won't work where any container overflows its parent (for example, if the CSS height is 0, and overflow isn't hidden). To get that working would be a lot more complex.

提交回复
热议问题