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

前端 未结 8 1561
悲哀的现实
悲哀的现实 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:15

    Interesting question. My immediate thought was to invert the color of the background as the text. This involves simply parsing the background and inverting its RGB value.

    Something like this: http://jsfiddle.net/2VTnZ/2/

    var rgb = $('#test').css('backgroundColor');
    var colors = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    var brightness = 1;
    
    var r = colors[1];
    var g = colors[2];
    var b = colors[3];
    
    var ir = Math.floor((255-r)*brightness);
    var ig = Math.floor((255-g)*brightness);
    var ib = Math.floor((255-b)*brightness);
    
    $('#test').css('color', 'rgb('+ir+','+ig+','+ib+')');
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题