Change text color based on brightness of the cover

2019-01-07 02:24发布

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 that changes a text's color or switches between predefined images/icons depending on the average brightness of the covered pixels of it's parent's background-image or -color.

If the covered area of it's background is rather dark, make the text white or switch the icons.

Additionally, it'd be great if the script would notice if the parent has no defined background-color or -image and then continue to search for the most nearest (from parent element to it's parent element..).

What do you think, know about this idea? Is there something similar out there already? script-examples?

Cheers, J.

7条回答
在下西门庆
2楼-- · 2019-01-07 03:04

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();
        }
        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 normalise 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.

查看更多
登录 后发表回答