简体   繁体   中英

Change colour of text foreground based on background color input

I have an input element which allows users to set the background colour of the input element.

When the user sets the background colour of the input element, I want the text in the input element to be a contrasting colour to the original colour.

For example: The user inputs "black" as the input background colour; then the text colour of the input will be white. However if the user inputs "white" as the input colour, the text colour would be black. (There are more cases than just black or white.)

How would I achieve this? I know that you can use another element on top of a background and set mix-blend-mode, but I don't want to because that would remove the point of the input.

Thanks!

You could calculate if black or white would have a higher contrast with the color given by the user based on the hexadecimal value of the color.

This link goes into detail on two ways to do this calculation. https://24ways.org/2010/calculating-color-contrast/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM